从Java调用Python(Anaconda)脚本(导入库问题)

时间:2019-06-26 08:29:17

标签: java python anaconda

我正在尝试从Java代码中调用python脚本。

public class PythonTest {
    public static void main(String[] args) throws IOException, ScriptException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder().inheritIO().command("C:/Users/emon/Anaconda3/python.exe",
                "forecast.py");
        Process process = pb.start();
        process.waitFor();
        InputStream inputStream = process.getInputStream();

        int i = 0;
        StringBuilder stringBuffer = new StringBuilder();
        while ((i = inputStream.read()) != -1) {
            stringBuffer.append((char) i);
        }
        System.out.println(stringBuffer.toString());
      }
}

基本上,我使用python脚本来预测一些给定的时间序列数据。我用facebook先知来做。另外,我使用了Anaconda。因此,在command括号中,我使用了C:/Users/emon/Anaconda3/python.exe

from fbprophet import Prophet
import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt

# plt.rcParams['figure.figsize'] = (20, 10)
# plt.style.use('ggplot')

sales_df = pd.read_csv('multiTimeline.csv')
sales_df['y_orig'] = sales_df['y']
sales_df['y'] = np.log(sales_df['y'])
model = Prophet()
model.fit(sales_df)
future_data = model.make_future_dataframe(periods=50, freq='w')
forecast_data = model.predict(future_data)
forecast_data[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
model.plot(forecast_data)
print(forecast_data)

# for index, row in forecast_data.iterrows():
#     print(
#         str(index) + " " + str(row['ds']) + " " + str(np.exp(row['yhat'])) + " " + str(
#             np.exp(row['yhat_lower'])) + " " + str(np.exp(row['yhat_upper'])))

# plt.show()

当我分别运行此python脚本时,我得到了预期的输出。但是,当我从Java代码运行它时,会出现此错误。

Traceback (most recent call last):
  File "google-trends-service/src/main/java/com/emon/forecast.py", line 1, in <module>
    from fbprophet import Prophet
  File "C:\Users\emon\Anaconda3\lib\site-packages\fbprophet\__init__.py", line 8, in <module>
    from fbprophet.forecaster import Prophet
  File "C:\Users\emon\Anaconda3\lib\site-packages\fbprophet\forecaster.py", line 15, in <module>
    import numpy as np
  File "C:\Users\emon\Anaconda3\lib\site-packages\numpy\__init__.py", line 140, in <module>
    from . import _distributor_init
  File "C:\Users\emon\Anaconda3\lib\site-packages\numpy\_distributor_init.py", line 34, in <module>
    from. import _mklinit
ImportError: DLL load failed: The specified module could not be found.

但是如果我只用python脚本替换

print("Hello world")

这将在Java控制台中提供预期的输出。

我看到了以前的帖子,但这些并不能解决我的问题。就是

Issue while calling Python(Anaconda) from Java

Calling Python script from JAVA MySQLdb imports

1 个答案:

答案 0 :(得分:0)

我的猜测是这是环境问题。您的Python脚本使用的模块具有与之关联的二进制组件(DLL)。手动运行脚本时,将以某种方式设置您的环境以找到该DLL。但是Java运行脚本的环境不同,并且找不到DLL。您的“ hello world”脚本运行良好,因为它不依赖于任何外部模块。

我建议您尝试重新安装Anaconda。