简体   繁体   中英

python script runs on its own through terminal but not when it's executed in Java with Runtime.getRuntime().exec()

python script runs on its own through terminal but not when it's executed in Java with Runtime.getRuntime().exec()

here's my script. i set my python interpreter in Eclipse the proper way and I don't know what to do.

#!/usr/bin python

import subprocess

def execute(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    proc_stdout = process.communicate()[0].strip()
    print (proc_stdout)

execute("command 1", "commnand 2", ...)

I can´t do much without seeing the java code (Most likely the problem is here).

I still can recommend you not to use "Runtime.getRuntime().exec()", use this instead (Might solve your problem):

String yourCommand = "Python ExampleScript.py";
ProcessBuilder pb = new ProcessBuilder(yourCommand);
Process p = pb.start();
p.waitFor();

Edit: If you are using complete paths, remember to use this:

(I had the same problem a couple weeks ago)

yourCommand.replaceAll("\\\\","/")

(I fixed a mistake in the code too)

So, I ended up fixing my Java process to a ProcessBuilder as you mentioned...thanks for that! The only extra thing I had to tweak was the commands. It needed to be a String[] object where the first 2 strings are "/bin/bash", "-c"

String[] cmds = { "/bin/bash", "-c", "python scriptName.py" };
ProcessBuilder pb = new ProcessBuilder(cmds);
Process p = pb.start();
p.waitFor();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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