Reputation: 956
I have the following code
public int fitsToJpg(String imagePath) throws IOException, InterruptedException{
String jpegFile = newJpegFileFullPath(imagePath);
String pythonPath = copyPythonFile();
Runtime r = Runtime.getRuntime();
String pythonExeString = String.format("python %s %s %s",pythonPath,imagePath, jpegFile);
Process p = r.exec(pythonExeString, new String[]{}, new File(System.getProperty("user.dir")));
if(p.waitFor() != 0) {
LoggingServices.createWarningLogMessage(IOUtils.toString(p.getErrorStream(), "UTF-8"), LOGGER);
return 1;
}
return 0;
}
that calls a python script to convert image formats. The problem I have is that when I run this code I get the following error
File "/home/scinderadmin/lib/dist/fits2jpg.py", line 2, in <module>
import cv2
File "/usr/lib64/python2.7/site-packages/cv2/__init__.py", line 5, in <module>
os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(__file__))
File "/usr/lib64/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'PATH'
Everything works if I run the python code directly. I think that this has something to do with the environment, but I cannot not figure out what I am doing incorrectly, any suggestions will be welcomed. by the way I am running this in a gnu Linux environment.
thanks,
es
Upvotes: 0
Views: 783
Reputation: 87154
The second argument to Runtime.exec()
is an array of stings containing the environment to pass to the child process. Your code explicitly sets that to an empty array. Because there is no PATH
environment variable in the child (or any env variable for that matter), Python throws an exception when it tries to lookup up its value.
You probably want the child to inherit the environment of the parent, in which case set envp
to null
:
Process p = r.exec(pythonExeString, null, new File(System.getProperty("user.dir")));
Of course this assumes that PATH
is actually set in the parent's environment. If it is not you can arrange for it to be by setting it prior to running the Java code, or explicitly by setting it in the envp
array passed to exec()
.
Upvotes: 1