这个脚本包含在我的Sping Boot 应用程序中。当我发送运行这个脚本的请求时,它就会自动运行。我使用py4j
库来建立Java和Python之间的连接。我使用这个方法从Java运行Python文件。
public void runScript(String file){
try {
String pythonScriptPath = "./src/main/java/com/api/air_quality/python/" + file + ".py";
String pythonExecutablePath = "C:\\Users\\KAVI\\AppData\\Local\\Programs\\Python\\Python310\\python.exe";
String command = pythonExecutablePath + " " + pythonScriptPath;
// Append the cached data to the command
for (Double value : airQualityDataCache.get()) {
command += " " + value;
}
Process process = Runtime.getRuntime().exec(command);
// output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// error
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errorReader.readLine()) != null) {
System.err.println(line);
}
int exitCode = process.waitFor();
if (exitCode != 0) {
System.out.println("Python script exited with code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
字符串
这是我想添加.env
变量的python文件。
from time import sleep
from dotenv import load_dotenv
from py4j.java_gateway import JavaGateway
import numpy as np
import pickle
import sys
import requests
import os
# to ignore warnings
import warnings
warnings.filterwarnings('ignore')
class AirHumidityModelPython:
def __init__(self):
self.gateway = JavaGateway()
self.java_model = self.gateway.entry_point
with open("./AI_Models/airHumidity_model.pkl", 'rb') as f:
self.model = pickle.load(f)
def predict_air_humidity(self, features):
try:
features_2d = np.array(features).reshape(1, -1)
prediction = self.model.predict(features_2d)[0]
url = os.getenv("SPRINGBOOT_URL_PYTHON")
spring_boot_url = url+"/airHumidity"
# Send the prediction to the Spring Boot endpoint
response = requests.post(spring_boot_url, json=float(prediction))
# print(response.text)
return prediction
except Exception as e:
# Handle any errors during prediction
return str(e)
if __name__ == "__main__":
load_dotenv()
# instance
air_humidity_model = AirHumidityModelPython()
# dummy_features = [[1.5, 2.3, 4.2, 5.1, 7.7, 9.4, 10.0]]
data_from_java = [float(arg) for arg in sys.argv[1:]]
result = air_humidity_model.predict_air_humidity(data_from_java)
# result = air_humidity_model.java_model.Message()
型
在这种情况下,工作流程是,用户将值数组发送到springboot后端,然后springboot服务运行上面的第一个方法。它将运行Python文件。然后它进行预测,并将预测值再次发送到springboot后端。Spring Boot缓存Python请求的值,并将其作为响应发送给用户。
问题是python-dotenv
在运行文件时出现此错误
import dotenv
ModuleNotFoundError: No module named 'dotenv'
型
我使用以下命令将正确的python-dotenv
库安装到了我的项目中。
pip3 install python-dotenv
型
也尝试过,
pip3.10 install python-dotenv
型
这个也是。
pip3 uninstall -U python-dotenv
型
然后,我直接运行Python文件,而不涉及Java,它工作得很好。
只有当Python文件通过Java方法运行时才会出现错误。其他Python导入不会出现任何错误。
1条答案
按热度按时间vzgqcmou1#
发生此错误是因为我从设备驱动器加载了
python.exe
,并从根venv
加载了lib
文件夹。当我试图从Java执行Python文件时,它无法加载一些需要激活的库。原因是执行程序和库位于不同的位置。因此,我修改了代码中的一些内容。在Python文件中,字符串
我附加了环境
venv
文件夹路径作为系统路径。现在这个文件路径就像它来自系统一样工作。在Java方法中,
型
我把python的可执行路径也改成了从
venv
根文件夹获取。现在这段代码运行良好,在部署中也不会有任何问题。