1. 程式人生 > 程式設計 >Vue3中watch的用法與最佳實踐指南

Vue3中watch的用法與最佳實踐指南

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)

執行結果: