Java调用Python

Java调用Python

因为大部分的工作都是用Python来进行开发,但遇到如果项目使用java代码来开发,所以就想到能不能利用java调用Python来实现。

package process_engine.build.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class CallPython {
	Process process;
	public void runPython() {
		try {
			// I have also test that we could try to fit a model, so the logic here is that we
			// try to call a process to run code with python engine and will wait until finished.
			process = Runtime.getRuntime().exec("C:\\Users\\Public\\anaconda\\python.exe C:\\new_sample.py");
			process.waitFor();
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println("Get error to call Python code: " + e);
		}
		InputStream inputStream = process.getInputStream();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
		String lineString;
		try {
			while ((lineString = bufferedReader.readLine()) != null) {
				System.out.println("get Python output: " + lineString);
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println("get python output error:" + e);
		}
	}
	
	public static void main(String[] args) {
		CallPython callPython = new CallPython();
		callPython.runPython();
	}
}

对应的Python代码

import numpy as np

print("Now is Python world")

data = np.random.randn(10)
print("Get sample data :", data)

运行结果:

posted @ 2021-07-08 16:09  蒙奇LU  阅读(119)  评论(0)    收藏  举报