[英]How to write an output of a command to stdout and a file in Python3?
我有一個Windows命令,要寫入標准輸出和文件。 現在,我的文件中只寫入了0
字符串:
#!/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
返回一個int(返回碼),這就是為什么在文件中寫入0
的原因。
如果要捕獲輸出,為什么不使用subprocess.run
呢?
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)
為了捕獲輸出p.stdout
,你必須到標准輸出重定向到subprocess.PIPE
。
現在p.stdout
保存輸出(以字節為單位),您可以將其保存到文件中。
Python版本<3.5的另一個選項是subprocess.Popen
。 這種情況的主要區別在於.stdout
是文件對象,因此您必須閱讀它。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.