问题
First off, there is a similar question here that wasn't ever really resolved.
I have a Python script that I want to execute from within my Java code. When I run the Python script on its own, it works properly. When I try to execute it from a Java process, I get an ImportError:
Traceback (most recent call last):
File "address_to_geocode.py", line 3, in <module>
from omgeo import Geocoder
ImportError: No module named omgeo
Per a suggestion from the linked question, I appended a direct path to the module in my Python import section to make sure the interpreter knows where to look, yet it still won't work:
import sys, os
sys.path.append('/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/omgeo')
from omgeo import Geocoder
My next move was to call the python script from a bash script (which again, works on its own), but when I call the bash script from Java, the same error persists. The issue, therefore seems to be on Java's end. Here is my java code:
Process p = runner.exec("python address_to_geocode.py");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String stdReader = null;
//Read output of command:
while((stdReader = stdInput.readLine())!=null) {
System.out.println(stdReader);
}
//Read any command errors:
while((stdReader = stdError.readLine())!=null) {
System.out.println(stdReader);
}
p.waitFor();
Is there anything wrong with my Java code or is this a bug? I appreciate any pointers.
回答1:
I solved it. It looks like ProcessBuilder
requires the full path not only to the python file itself, but to python:
ProcessBuilder("/Library/Frameworks/Python.framework/Versions/2.7/bin/python",absolute_file_path);
This solves the issue.
回答2:
Find your python bin location
$ cat ~/.bash_profile
Java code
ProcessBuilder pb = new ProcessBuilder("/Users/micklin/anaconda2/bin/python","sentiment.py",done.toString());
code above is put in TweetFeeder.java so that .py file can be put under the project root
来源:https://stackoverflow.com/questions/28487118/python-importerror-when-calling-python-script-from-java