JavaDemo——Java通过Runtime调用py脚本

python脚本test.py:

#!/usr/bin/env python3
# coding=utf-8

# import sys
# import os
# curpath = os.path.abspath(os.path.dirname(__file__))
# sys.path.append(os.path.split(curpath)[0])

print('测试+++hello python')

javaDemo:

/**
 * 2020年7月3日上午10:57:19
 */
package testcallpython;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author XWF
 *
 */
public class TestCallPython {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("start test");
		String prog = "python src/testcallpython/test.py";
		try {
			Process proc = Runtime.getRuntime().exec(prog);
			BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream(), "gbk"));
			String s = null;
			while((s = br.readLine()) != null) {
				System.out.println(s);
			}
			int result = proc.waitFor();
			System.out.println("命令执行结果:" + result);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("test stop");
	}

}

结果:

JavaDemo——Java通过Runtime调用py脚本_第1张图片

 

 

参考:

https://www.cnblogs.com/zhigu/p/10935182.html

https://blog.csdn.net/ltf971101/article/details/105437256/

你可能感兴趣的:(JavaDemos,java调用Python脚本)