0

I am using subprocess.run to run a command and print output to a file.

I am able to print correct output for 'python --version' since the answer is 'Python 3.6.5', but when i run the same command for 'java -version' there is no output in text file, but it is reflected in console.

Maybe it's because the output of 'java -version' is spread in three lines!

import subprocess
import os
import sys
sys.stdout = open('outputCS.txt','wt')

result = subprocess.run('python --version', stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
tarun
  • 41
  • 1
  • 6
  • 2
    `java -version` outputs to stderr, not stdout. – interjay May 20 '19 at 13:32
  • @interjay yes, in which case you'd want to add `stderr=subprocess.PIPE` as an argument to `subprocess.run()` in order to capture that. After which you'd access it with `result.stderr.decode('utf-8')`, just like you're currently doing with `stdout` – Green Cloak Guy May 20 '19 at 13:33
  • that solved the issue.. thanks!! @GreenCloakGuy – tarun May 21 '19 at 05:19

1 Answers1

0
import subprocess

f = open("stuff", "wt")
subprocess.run(['python', '--version'], stdout=f, stderr=f)
subprocess.run(['java', '-version'], stdout=f, stderr=f)
dgan
  • 1,349
  • 1
  • 15
  • 28
  • i can not use 'with' loop because i have other methods which are using this line: sys.stdout = open('outputCS.txt','wt') as a global parameter to open file to write the output. – tarun May 20 '19 at 13:43
  • 1
    I am not using any loop?.. But if you are talking about `with` statement, then just delete it, and use file descriptor from elsewhere. Edited – dgan May 20 '19 at 13:45