问题
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