简体   繁体   中英

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 subprocess

with 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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM