Runtime.getRuntime().exec()实现Java调用python程序
2018-02-26 15:41
639 查看
Runtime.getRuntime().exec()实现Java调用python程序
在使用jython实现Java调用python程序,如果python程序中包含有第三方库(如numpy),则会报如下错误:Exception in thread "main" Traceback (innermost last): File "pyfile/detect.py", line 3, in ? ImportError: no module named numpy
推荐使用的方法是使用Runtime.getRuntime().exec()来实现Java调用python,调用代码如下所示:
package com.xiaoxian.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test2 { public static void main(String[] args) throws IOException, InterruptedException { System.out.println("start python"); //需传入的参数 String a = "aaa", b = "bbb", c = "cccc", d = "dddd"; //设置命令行传入的参数 // String[] arg = new String[]{"python", "pyfile/test2.py", a, b, c, d}; String[] arg = new String[]{"python", "pyfile/detect.py"}; Process pr = Runtime.getRuntime().exec(arg); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { // line = decodeUnicode(line); System.out.println(line); } in.close(); System.out.println("end"); pr.waitFor(); } }其中
String[] arg = new String[]{"python", "pyfile/test2.py", a, b, c, d};可用于设置传入python程序的参数。
两个注意事项:一、python程序中不能含有中文;
二、python使用的文件路径最好使用绝对路径;
相关文章推荐
- 使用Runtime.getRuntime().exec()在java中调用python脚本
- java程序中调用其他工具打开文本---Runtime.getRuntime().exec()的使用
- 使用Runtime.getRuntime().exec()在java中调用python脚本
- java 利用Runtime.getRuntime().exec()调用python脚本并传参
- java 利用Runtime.getRuntime().exec()调用python脚本并传参
- 使用Runtime.getRuntime().exec()在java中调用python脚本
- [转]java调用外部程序Runtime.getRuntime().exec
- java.lang.Runtime.getRuntime().exec 调用后,等待被调用程序结束后再继续执行
- java 利用Runtime.getRuntime().exec()调用python脚本并传参
- java调用命令行Runtime.getRuntime().exec()函数碰到的阻塞问题
- 通过Runtime.getRuntime().exec调用底层Linux下的程序或脚本
- 如何在JAVA代码中执行 exec master..xp_cmdshell @cmd // 当作SQL语句调用就成了 或者调用 Runtime.getRuntime().exec
- 在runtime.getruntime().exec调用程序时路径的问题的解决方案列表
- Android: 通过Runtime.getRuntime().exec调用底层Linux下的程序或脚本
- java调用命令行Runtime.getRuntime().exec()阻塞问题
- MAC(苹果)-JAVA Runtime.exec调用 .app 程序
- Eclipse下使用Runtime.getRuntime().exec启动java程序的问题
- Android: 通过Runtime.getRuntime().exec调用底层Linux下的程序或脚本
- Runtime.getRuntime().exec()调用外部程序
- Java技巧:使用Runtime.exec重定向本地程序Java技巧:使用Runtime.exec重定向本地程序调用调用