[英]Including Python Script in Spring Boot Application with Jython fails - module not found
我正在嘗試習慣 python+java 交互,所以我寫了一個小 python 腳本,我想從我的Spring Boot Application
執行該腳本。 該腳本位於(相對於.java
文件)路徑/scripts_py/getStockPrice.py
中,其中包含getStockPrice
-方法(請參見下面的代碼)。 所以我集成了jython
並嘗試執行以下CronJob
:
@Component
public class CronService {
private PythonScriptSingleton pss = PythonScriptSingleton.getInstance();
private final Logger logger = LoggerFactory.getLogger(CronService.class);
//call every 5 sec
@Scheduled(fixedRate = 5000)
public void initStockPriceAPICall() {
this.getStockPrice("NFLX");
}
public void getStockPrice(String ticker) {
String result = (String) (Object) this.pss.getFunc_getPriceForTicker().__call__(new PyString(ticker));
try {
logger.info("Price is " + result);
} catch (NullPointerException e) {
logger.info("Catched NPE");
}
}
}
PythongScriptSingleton
(這個想法是,我可能需要多次執行該腳本 - 所以我嘗試使用 go 來獲取此singleton
實例的 singleton 實例:每次都需要重新編譯該腳本:
public class PythonScriptSingleton {
private static PythonScriptSingleton ps;
public static PythonScriptSingleton getInstance() {
if (ps == null) {
ps = new PythonScriptSingleton();
ps.initScript();
}
return ps;
}
private PyObject func_getPriceForTicker;
private PythonScriptSingleton() {
}
private void initScript() {
PythonInterpreter interpreter = new PythonInterpreter();
String fileUrlPath = "/scripts_py";
String scriptName = "getStockPrice.py";
interpreter.exec("import sys\n" + "import os \n" + "sys.path.append('" + fileUrlPath + "')\n" + "from "
+ scriptName + " import * \n");
String funcName = "getStockPrice";
PyObject someFunc = interpreter.get(funcName);
this.func_getPriceForTicker = someFunc;
interpreter.close();
}
public PyObject getFunc_getPriceForTicker() {
return func_getPriceForTicker;
}
}
Python 腳本:
from yahoo_fin import stock_info as si
def getStockPrice(ticker):
price = si.get_live_price(ticker)
return price
我正在使用嵌入式tomcat
和Spring Boot
(可執行JAR
)和jython-standalone 2.7.2
:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
我一直遇到的錯誤說,該腳本未定義-我嘗試在有和沒有文件結尾( .py
)的情況下定義它,兩者都沒有改變任何東西:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.fr.stockticker.pythoninteraction.CronService]: Constructor threw exception; nested exception is Traceback (most recent call last):
File "<string>", line 4, in <module>
ImportError: No module named getStockPrice
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1312) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 81 common frames omitted
Caused by: org.python.core.PyException: ImportError: No module named getStockPrice
at org.python.core.Py.ImportError(Py.java:329) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.import_first(imp.java:1230) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.import_module_level(imp.java:1361) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.importName(imp.java:1528) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.ImportFunction.__call__(__builtin__.java:1285) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.PyObject.__call__(PyObject.java:433) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.__builtin__.__import__(__builtin__.java:1232) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.importAll(imp.java:1647) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.pycode._pyx0.f$0(<string>:4) ~[na:na]
at org.python.pycode._pyx0.call_function(<string>) ~[na:na]
at org.python.core.PyTableCode.call(PyTableCode.java:173) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.PyCode.call(PyCode.java:18) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.Py.runCode(Py.java:1687) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.Py.exec(Py.java:1731) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.util.PythonInterpreter.exec(PythonInterpreter.java:268) ~[jython-standalone-2.7.2.jar:2.7.2]
at de.fr.stockticker.pythoninteraction.PythonScriptSingleton.initScript(PythonScriptSingleton.java:28) ~[classes/:na]
at de.fr.stockticker.pythoninteraction.PythonScriptSingleton.getInstance(PythonScriptSingleton.java:13) ~[classes/:na]
at de.fr.stockticker.pythoninteraction.CronService.<init>(CronService.java:12) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_251]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_251]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 83 common frames omitted
我能夠使用 Jython 部分運行您的程序 - 我無法從內部依賴 numpy 的雅虎獲取庫存流程,看起來 Jython 不支持 numpy,因為它是 cpython 庫。
private void initScript() {
PythonInterpreter interpreter = new PythonInterpreter();
String fileUrlPath = "/users/sagar/demo/src/main/resources/python";
interpreter.exec("import sys");
interpreter.exec("sys.path.append('" + fileUrlPath + "')");
interpreter.exec("from getStockPrice import *"); this.func_getPriceForTicker =
interpreter.get("getStockPrice", PyFunction.class);
interpreter.close();
}
你將能夠克服你的錯誤,但你會看到錯誤
Missing required dependencies ['numpy']
所以我嘗試使用另一個 java python 庫jep並進行如下更改
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
private final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
//call every 5 sec
@Scheduled(fixedRate = 5000)
public void initStockPriceAPICall() throws JepException {
this.getStockPrice("NFLX");
}
private void getStockPrice(String ticker) throws JepException {
try (Interpreter interp = new SharedInterpreter()) {
String fileUrlPath = "/users/sagar/demo/src/main/resources/python";
interp.exec("import sys");
interp.exec("sys.path.append('" + fileUrlPath + "')");
interp.exec("from getStockPrice import *");
interp.set("ticker", ticker);
interp.exec("price = getStockPrice(ticker)");
Object result = interp.getValue("price");
logger.info("Price is " + result);
}
}
}
pom.xml
<dependency>
<groupId>black.ninia</groupId>
<artifactId>jep</artifactId>
<version>3.9.0</version>
</dependency>
確保安裝 jep 模塊 - 它有本地庫
pip install jeb
添加java庫路徑加載native庫
-Djava.library.path=/usr/local/lib/python2.7/site-packages/jep
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.