Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...