2017-08-11 45 views
0

我有以下代码运行从Java的Python脚本产生KeyError异常

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; 
} 

调用一个python脚本转换图像格式。我的问题是,当我运行此代码我碰到下面的错误

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' 

一切正常,如果我直接运行Python代码。我认为这与环境有关,但我不知道我做错了什么,任何建议都会受到欢迎。我在gnu Linux环境下运行这个程序。

感谢,

ES

回答

1

的第二个参数是Runtime.exec()含有环境传递给子进程蜇的阵列。你的代码明确地将它设置为一个空数组。由于子项中没有PATH环境变量(或任何用于该事件的env变量),因此Python在尝试查找其值时会引发异常。

你可能希望孩子继承父的环境,在这种情况下,设置envpnull

Process p = r.exec(pythonExeString, null, new File(System.getProperty("user.dir"))); 

当然这个假设PATH在父母的环境中实际设置。如果不是的话,你可以通过在运行Java代码之前设置它,或者通过将其设置在传递到exec()envp数组中进行设置来安排它。

+0

有趣的是,我查了第三个参数,但没有第二个参数。 – Goozo