【问题标题】:How to write an output of a command to stdout and a file in Python3?如何将命令的输出写入标准输出和 Python3 中的文件?
【发布时间】:2018-09-09 05:48:01
【问题描述】:

我有一个 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)

【问题讨论】:

  • 您是否尝试过丢弃子进程并简单地编写任何字符串文字?
  • 现在我有了,它可以工作,所以我编辑了我的问题的标题。

标签: python


【解决方案1】:

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 版本 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)

【讨论】:

  • 谢谢! subprocess.PIPE 是什么意思?不幸的是,我使用 Python 3.4.3 来兼容 XP,但 subprocess.run 仅适用于 3.5+。我可以从未来以某种方式导入它吗?我不知道如何像这里建议的那样修补它stackoverflow.com/questions/40590192/…
  • 这也不会写入控制台,所以我添加了subprocess.call(cmd)。感谢您解释 callrunpopen 之间的差异。
  • 是的,它不会打印,因为输出被重定向。但是为什么不使用print 而不是调用两次命令呢?我更新了我的代码来举个例子。
猜你喜欢
  • 2019-06-19
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多