简体   繁体   中英

How can I get output from subprocess.check_output if the subprocess is a java program(with Command-line arguments)?

I have the following java code: (HelloWorld.class is in bin folder):

package Hello;
public class HelloWorld {
    public static void main(String[] args) {
    System.out.println("Hello World" + args[1]);
    }
}

I want to call this java code from a python script and pass some command-line arguments to it.

So my python code is:

cmd = ["java","-classpath","bin/","Hello.HelloWorld","arguement1","arguement2"]
try:
    print subprocess.check_output(cmd,stderr=subprocess.STDOUT)
except: subprocess.CalledProcessError:
    print ('calling '+ ' '.join(cmd) +' failed\n')

If I run this code, I will get the no output from java code, and also get output "calling java -classpath bin/ Hello.HelloWorld arguement1 arguement2 failed".

But if I run:

java -classpath bin/ Hello.HelloWorld arguement1 arguement2 

in terminal, the java code will print the string.

So where is wrong of my python code?

You don't see the output because both stdout and stderr are captured by check_output(stderr=STDOUT) and java exits with a non-zero exit status that leads to the exception and that is why you see ".. failed" message.

To get subprocess' output in the exception handler except CalledProcessErrror as e: , access e.output attribute.

If you don't need to capture the output then just call call() instead:

import subprocess

subprocess.check_call(cmd)

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