使用Runtime.getRuntime()在java中执行python文件
public class JavaPythonFile {
public static void main(String[] args) throws IOException, InterruptedException {
try {
Process process = Runtime.getRuntime().exec("python D:\\\\pythontext\\keshe.py"); //放python文件的绝对路径
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
process.waitFor();
} catch (IOException e) {
e.printstacktrace();
} catch (InterruptedException e) {
e.printstacktrace();
}
}
}
另外在java中运行时,如果出现乱码,
因为Python安装在Windows环境下的默认编码格式是GBK!!!
import io
import sys
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
注:一定要添加到其他依赖模块import之前