[英]Command executed from terminal, failed from Java using ProcessBuilder
I'm trying to execute a command in my terminal. 我正在尝试在终端中执行命令。 The problem is, when I execute the command in terminal, it succeed, but when I run the command from java, the command is executed but, I got an error message showing me that some python module is missing.
问题是,当我在终端中执行命令时,它成功了,但是当我从java运行命令时,命令被执行但是,我收到一条错误消息,显示我缺少一些python模块。
try{
String[] list = { "python3", "script.py" };
ProcessBuilder pb = new ProcessBuilder(list);
pb.directory(
new File("/home/script"));
System.out.println("" + pb.directory());
Process process = pb.start();
InputStream str = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(str);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);}
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
process.waitFor();
process.destroy();
}catch (Exception ex) {
ex.printStackTrace();
}
The error message: 错误消息:
/home/script
Output of running [] is:Traceback (most recent call last):
File "scraper.py", line 8, in <module>
from selenium import webdriver
ModuleNotFoundError: No module named 'selenium'
value is : null
PS: When I execute the command directly from terminal, everything works good, I don't get the missing module error. PS:当我直接从终端执行命令时,一切正常,我没有得到丢失的模块错误。
Similar to Java, python allows to import other stuff. 与Java类似,python允许导入其他东西。 That message tells you that your python script wants to use the module
selenium
, but can't find it. 该消息告诉您,您的python脚本想要使用模块
selenium
,但无法找到它。
Most likely you have some special ENV var setup when running commands manually in a shell/console. 在shell /控制台中手动运行命令时,很可能会有一些特殊的ENV var设置。 So check your .bashrc or .initrc or whatever defines your ENV variables.
因此,请检查.bashrc或.initrc或其他定义ENV变量的内容。 On a unix system, typing the command
env
might show you all settings, too. 在unix系统上,键入命令
env
也可能会显示所有设置。 Simply check if the env var PYTHONPATH is setup. 只需检查是否设置了env var PYTHONPATH。
As that call works from the command line, then for sure, the module is installed on your system. 由于该调用是从命令行进行的,因此可以肯定,该模块已安装在您的系统上。 Your only problem is that python can't find it when you invoke that script through the Java ProcessBuilder!
您唯一的问题是当您通过Java ProcessBuilder调用该脚本时,python无法找到它!
One solution might be that you "manually" adjust the PYTHONPATH from within your script. 一种解决方案可能是您在脚本中“手动”调整PYTHONPATH。 Thus: figure the correct setup for PYTHONPATH, then update your script to "do the right thing".
因此:为PYTHONPATH设置正确的设置,然后将脚本更新为“做正确的事情”。
For further details, see the python documentation ! 有关更多详细信息,请参阅python 文档 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.