1,Java调用python(不含第三方模块)
Properties props = new Properties();
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site","false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys");
PySystemState sys = Py.getSystemState();
interpreter.execfile("C:/Users/28985/AppData/Local/Programs/Python/Python35/Lib/site-packages/nltk/hello.py");
https://blog.csdn.net/hzw19920329/article/details/77509497
2.含有第三方模块
在测试过程中,直接在python上面运行的文件是可以直接进行调用的,然后新建的一个文本(ANSI),然后在将可运行代码保存到文本,在进行测试是不行的,原因在于两个文件的编码不一致,建议采用编译器通过的文件(UTF-8)进行测试,也可以将新建的文件另存为一份,修改其编码为UTF-8即可
// private static final String PY_URL = "D:/test1.py";
// private static final String PY_URL = "C:/Users/28985/AppData/Local/Programs/Python/Python35/test2.py";
private static final String PY_URL = "D:/hello.py";
private static final String DATA_SWAP = "name.txt";
private static final String PATH = "D:\\ansj";
// 测试码
public static void main(String[] args) {
try {
String[] arguments = new String[] {"python", PY_URL, DATA_SWAP,PATH};
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader( process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println("line====>>>>"+line);
}
in.close();
int re = process.waitFor();
System.out.println("re====>>>>"+re);
} catch (Exception e) {
e.printStackTrace();
}
}
interpreter.execfile(PY_URL);
PyFunction func = (PyFunction)interpreter.get("adder",PyFunction.class);
int a = 2010, b = 2 ;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + pyobj.toString());