简体   繁体   English

Java Runtime.getRuntime()。exec()将不会执行python.exe

[英]Java- Runtime.getRuntime().exec() will not execute python.exe

For a project I need to start python.exe via Runtime.getRuntime.exec(). 对于项目,我需要通过Runtime.getRuntime.exec()启动python.exe。 However, when I try to run it it won't execute, but it doesn't throw up an IOException. 但是,当我尝试运行它时,它不会执行,但是不会抛出IOException。 Here's the code: 这是代码:

try 
    {

        Process process=Runtime.getRuntime().exec("C:\\Program Files (x86)\\PythonTest\\python.exe");
    } 
    catch (IOException e) 
    {
        System.out.println("Cannot find python.exe");
        e.printStackTrace();
    }    

You need to get the output from the process and ( waitFor() it to finish). 您需要从流程中获取输出,并(通过waitFor()完成)。 Something like, 就像是,

final String cmd = "C:/Program Files (x86)/PythonTest/python.exe";
Process p = Runtime.getRuntime().exec(cmd);
final InputStream is = p.getInputStream();
Thread t = new Thread(new Runnable() {
  public void run() {
    InputStreamReader isr = new InputStreamReader(is);
    int ch;
    try {
      while ((ch = isr.read()) != -1) {
        System.out.print((char) ch);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
});
t.start();
p.waitFor();
t.join();

To actually do something with python you'll want to get the OutputStream . 要实际使用python做某事,您需要获取OutputStream

I think that the problem is due to eval incorrectly splitting the command string. 我认为问题是由于eval错误地分割了命令字符串。 My understanding is that exec("C:\\\\Program Files (x86)\\\\PythonTest\\\\python.exe") will attempt to run an application called "C:\\\\Program" , passing it 2 command line arguments. 我的理解是exec("C:\\\\Program Files (x86)\\\\PythonTest\\\\python.exe")将尝试运行名为"C:\\\\Program"的应用程序,并向其传递2个命令行参数。

Try this instead: 尝试以下方法:

 exec(new String[]{"C:\\Program Files (x86)\\PythonTest\\python.exe"});

The exec(String, ...) command line parsing is primitive, and often has the incorrect behaviour from the programmer's perspective. exec(String, ...)命令行解析是原始的,从程序员的角度来看,通常行为不正确。 The best bet is often to split the command and arguments yourself. 最好的选择通常是自己分割命令和参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM