1

Here is my code

    f = os.popen("java -version")
    for i in f.readlines():
        print "result, ", i,

Basically I want the output of java -version to be stored in f. What happens is, after the first line of the script executes, the java -version information is printed out, but not stored in f, hence the third line of code is not executed at all. This code works for other commands such as "ls -la", but not for java -version. Any ideas as to why?

Thanks in advance.

1
  • 3
    output of java -version goes to stderr Commented Aug 15, 2012 at 10:23

2 Answers 2

1

Since java -version goes to stderr, not to stdin, you have to redirect it:

f = os.popen("java -version 2>&1")
for i in f.readlines():
    print "result, ", i,

better yet, use the subprocess module, which is designed to make this kind of things easier:

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

Comments

1

try something like:

from subprocess import Popen, PIPE
stdout,stderr= Popen(['java','-version'], shell=False, stderr=PIPE).communicate()
print(stderr)

output:

b'java version "1.6.0_20"\nOpenJDK Runtime Environment (IcedTea6 1.9.13) (6b20-1.9.13-0ubuntu1~10.10.1)\nOpenJDK Client VM (build 19.0-b09, mixed mode, sharing)\n'

1 Comment

@user1410747 my mistake it should be stderr=PIPE, now it'll work.

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.