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?

1

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

2 Comments

There's no reason to resort to Popen here, you can pass stderr=subprocess.STDOUT to subprocess.check_output easliy enough
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.