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之前