Skip to content Skip to sidebar Skip to footer

How To Write An Output Of A Command To Stdout And A File In Python3?

I have a Windows command which I want to write to stdout and to a file. For now, I only have 0 string writen in my file: #!/usr/bin/env python3 #! -*- coding:utf-8 -*- import subp

Solution 1:

subprocess.call returns an int (the returncode) and that's why you have 0 written in your file. If you want to capture the output, why don't you use subprocess.run instead?

import subprocess

cmd = ['netsh', 'interface', 'show', 'interface']
p = subprocess.run(cmd, stdout=subprocess.PIPE)
with open('my_file.txt', 'wb') as f:
    f.write(p.stdout)

In order to capture the output in p.stdout, you'll have to redirect stdout to subprocess.PIPE. Now p.stdout holds the output (in bytes), which you can save to file.


Another option for Python versions < 3.5 is subprocess.Popen. The main difference for this case is that .stdout is a file object, so you'll have to read it.

import subprocess

cmd = ['netsh', 'interface', 'show', 'interface']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out = p.stdout.read()
#print(out.decode())  
with open('my_file.txt', 'wb') as f:
    f.write(out)

Post a Comment for "How To Write An Output Of A Command To Stdout And A File In Python3?"