2

I tried os.popen and the like ways. But it does not seem to work for me. I'm wondering if there's anything different between a command 'echo xxxx' and 'java -version', and how can I get 'java -version' output with python code.

3

3 Answers 3

6
import subprocess
sp = subprocess.Popen(["java", "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print sp.communicate()
print sp.wait()

is the real way to go.

An even simpler way could be

print subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
Sign up to request clarification or add additional context in comments.

Comments

2

The difference is that java -version prints to stderr instead of stdout. You can check the stderr of the command using subprocess.Popen (better) or redirect stdout to stderr manually:

java -version 2>&1

Comments

-2

Yes, the difference is that java -version goes to the stderr stream. Try popen3 http://docs.python.org/library/popen2.html

3 Comments

"Deprecated since version 2.6: This module is obsolete. Use the subprocess module."
So what, it's still commonly used. Lots of ppl use os.popen and I doubt it's going away in the 2.x branch (which is pretty much dead by now anyway).
If something is deprecated I wouldn't recommend it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.