2021-07-03java中运行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之前

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...