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 subprocesswith open('auto_change_ip.txt', 'w') as f:print(subprocess.call(['netsh', 'interface', 'show', 'interface']), file=f)
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 subprocesscmd = ['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 subprocesscmd = ['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)