您的位置:首页 > 编程语言 > Python开发

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使用的文件路径最好使用绝对路径;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: