Calling Python script from Java code using Runtime.exec() : ImportError: No module named sklearn

孤者浪人 提交于 2021-02-11 12:48:59

问题


I Have a Java program that calls a python script. That python script has the following imports

 import numpy as np
 from sklearn import metrics

On my mac, i already have python 2.7, i now installed python 3.7 I also installed numpy, scipy and sklearn modules using pip3.

In Intellij, i selected the python 3.7 interpreter and Java1.8 for my project

When i run the java program which calls python script using the command

 Process p = Runtime.getRuntime().exec("python /mydir/report.py");

i get this error

ImportError: No module named sklearn

My suspicion is that somehow intellij is using python 2.7 and python 3.7. The reason is when i run the python script directly in pyCharm using python2.7, i get the same error but not with 3.7

Please help resolve this, i already went through all the related SO questions and were not helpful for this situation


回答1:


Try using 'python3' :

Process p = Runtime.getRuntime().exec("python3 /mydir/report.py");

Or alternatively, you can try:

ProcessBuilder pb = new ProcessBuilder("python", "/mydir/report.py"); /*Or python3*/
Process process = pb.start();

For detailed usage of ProcessBuilder : https://examples.javacodegeeks.com/core-java/lang/processbuilder/java-lang-processbuilder-example/




回答2:


Make sure that you are using the correct version of python. In some OS's, python3.x is called on the command line as python3 and therefore you will need to change your exec code to "python3 /mydir/report.py".

If you are using python3, pip will be shipped with the install, and therefore, you may also need to run pip install -U scikit-learn.




回答3:


The answer is in your question: No module named sklearn. Try to install sklearn :

pip install -U scikit-learn


来源:https://stackoverflow.com/questions/56964203/calling-python-script-from-java-code-using-runtime-exec-importerror-no-modu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!