Java调用python的代码如下:
package reptile;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reptile {
public static void main(String[] args) {
try {
String exe = "python";
String command = "main_init.py";
String[] cmdArr = new String[] { exe, command };
File file=new File("C:\\Users\\i\\Desktop\\graduate\\sll");
Process process = Runtime.getRuntime().exec(cmdArr,null,file);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while( ( line = in.readLine() ) != null ) {
System.out.println(line);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
需要注意的是:
- 使用绝对路径,写到需要调用的py文件的当前目录即可
- pycharm里python虚拟环境和cmd中python的环境不一样,所以如果发现运行此代码依旧不能实现调用,建议去cmd下面pip list看一下缺哪些库,然后补上即可。当然也有其他的修改方式,以后补充。