JAVA调用Python及Shell

这是最近项目中有涉及到的一个点,网上有很多这样的方法,我只是想作为自己的工作日记保存下来,也当做一个总结。

其中,这涉及到一个类叫process,其实大家一看代码就知道了。

//String cmd = "sh /home/test/test.sh“ ;

String cmd = "python /home/test/test.py“ ;//windows下一样  只是要注意路径的格式,调用bat其实也类似

 Process process  = Runtime.getRuntime().exec(cmd);  

python或shell脚本有返回值的,可读取process.getInputStream()流,IO流的读写就不详细说了。


另外,也可用Jython来更加灵活的调用python脚本或代码,具体做法先下载jar包导入,主要用到其中的PythonInterpreter类。

Exp:

 PythonInterpreter interpreter = new PythonInterpreter(); 

 interpreter有很多重载的执行方法,可自行查询API选用。

若想调用python脚本中的某些方法,可单独获取,参照反射机制

 PyFunction func = (PyFunction)interpreter.get("testFun",PyFunction.class); 

testFun为python中的方法名,若方法需要传参,可通过下面方法传参执行

 String a = "hello";
String b = "world";
       PyObject pyobj = func.__call__(new PyString(a), new PyString(b));  


end。

猜你喜欢

转载自blog.csdn.net/u013361107/article/details/76948785