-1

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 subprocess

with open('auto_change_ip.txt', 'w') as f:
    print(subprocess.call(['netsh', 'interface', 'show', 'interface']), file=f)
Hrvoje T
  • 3,365
  • 4
  • 28
  • 41

1 Answers1

2

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)
t.m.adam
  • 15,106
  • 3
  • 32
  • 52
  • Thank you! What does `subprocess.PIPE` mean? Unfortunately, I use Python 3.4.3 for XP compatibility, but `subprocess.run` is only for 3.5+. Can I import it somehow from future? I don't know how to patch it like suggested here https://stackoverflow.com/questions/40590192/getting-an-error-attributeerror-module-object-has-no-attribute-run-while – Hrvoje T Mar 30 '18 at 08:33
  • This doesn't write to console too, so I added `subprocess.call(cmd)`. Thank you for explaining a diffrence between `call`, `run` and `popen`. – Hrvoje T Mar 30 '18 at 09:34
  • 1
    Yes, it won't print because the output is redirected. But why don't you use `print` instead of calling the command twice? I updated my code to give an example. – t.m.adam Mar 30 '18 at 09:44