2021-07-03(java中运行python代码)

2021/7/3 11:24:19

本文主要是介绍2021-07-03(java中运行python代码),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用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();
        } 
	}
}

注意 python中如果有图片,一定要用图片的绝对路径

另外在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之前



这篇关于2021-07-03(java中运行python代码)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程