0

I'm new in this, I want to write the output of java version in a file text.

I used this from another post I saw:

import subprocess

with open('C:\Python27\ping.txt','w') as out:
    out.write(subprocess.check_output("ping www.google.com"))

And that worked, wrote the output of "ping www.google.com" to a text file.

I thought that if I just change the "ping www.google.com" to "java -version" everything would be solved.

Like this:

import subprocess

with open('C:\Python27\java.txt','w') as out:
    out.write(subprocess.check_output("java -version"))

But this did not work me, this just print the output of "java -version" to console, and didn't write it in the text file.

Can anyone help me?

SiHa
  • 7,830
  • 13
  • 34
  • 43
  • The version goes to `stderr` not `stdout`. See [my answer](https://stackoverflow.com/a/31808419/1084416) to [this question](https://stackoverflow.com/questions/31807882/get-java-version-number-from-python) – Peter Wood Sep 22 '17 at 06:53

1 Answers1

0

You could try to use stderr:

from subprocess import Popen, PIPE, STDOUT

with open('C:\Python27\java.txt','w') as out:
  cmd = 'java -version'
  p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
  out.write(p.stderr.read())
Roman Mindlin
  • 852
  • 1
  • 8
  • 12
  • There's no reason to resort to `Popen` here, you can pass `stderr=subprocess.STDOUT` to `subprocess.check_output` easliy enough – Jon Clements Sep 22 '17 at 06:57
  • @JonClements I believe that good practice is to use `Popen` in any case since it is non-blocking. But you are right - `stderr=subprocess.STDOUT` is enough. – Roman Mindlin Sep 22 '17 at 07:06