问题描述
某一功能是通过python项目实现的,但是主项目是java项目,此时希望在java项目中调用python进程。
方法
import lombok.extern.slf4j.Slf4j;import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
@Slf4j
public class PythonProcess {public static void main(String[] args) {try {// 创建一个ProcessBuilder对象,指定要执行的Python脚本和参数ProcessBuilder pb = new ProcessBuilder("C:/Users/18234/.conda/envs/new/python", "E:/ideaCode/code/ui.py");// 设置Python环境变量,指定Python库路径Map<String, String> env = pb.environment();env.put("PYTHONPATH", "C:/Users/18234/.conda/envs/new");System.out.println("Virtual environment path: " + env.get("PYTHONPATH"));
// pb.directory(new File("path/to/working/directory"));pb.directory(new File("E:/ideaCode/code/"));// 启动进程Process process = pb.start();// 添加shutdown hookRuntime.getRuntime().addShutdownHook(new Thread() {@Overridepublic void run() {System.out.println("Shutdown hook triggered. Closing Python process...");process.destroy();}});// 获取进程的输出流//注意设置编码格式为utf-8BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));String line;while ((line = reader.readLine()) != null) {// 处理Python进程的输出System.out.println(line);}BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));String errorLine;while ((errorLine = errorReader.readLine()) != null) {System.err.println(errorLine);}// 等待Python进程执行完毕int exitCode = process.waitFor();System.out.println("Python进程执行完毕,退出码:" + exitCode);} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}
遇到的问题
调用python项目后打印python进程的输入中文乱码
解决办法
在python项目增加以下代码,设置编码格式也为utf-8,java项目和python中编码格式保持一致即可。
import syssys.stdout.reconfigure(encoding='utf-8')