user1410747
user1410747

Reputation: 99

Cannot capture output of java -version using os.popen

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.

Upvotes: 1

Views: 688

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

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'

Upvotes: 1

georg
georg

Reputation: 214949

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)

Upvotes: 1

Related Questions