让 Python 自己的prints 去终端和文件并不难:
>>> import sys
>>> class tee(object):
... def __init__(self, fn='/tmp/foo.txt'):
... self.o = sys.stdout
... self.f = open(fn, 'w')
... def write(self, s):
... self.o.write(s)
... self.f.write(s)
...
>>> sys.stdout = tee()
>>> print('hello world!')
hello world!
>>>
$ cat /tmp/foo.txt
hello world!
这应该适用于 Python 2 和 Python 3。
要类似地直接从子命令输出,不要使用
retvalue = subprocess.check_call(cmd, shell=True)
这让cmd 的输出转到其常规的“标准输出”,而是自己抓取并重新发出,如下所示:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
so, se = p.communicate()
print(so)
retvalue = p.returncode
假设您不关心标准错误(仅标准输出)并且来自cmd 的输出量相当小(因为.communicate 将数据缓冲在内存中)——如果有的话,很容易调整假设与您真正想要的不相符。
编辑:OP 现在已在对此答案的长评论中阐明了规范:
- 如何在
存储在输出文件中的问题
也?例如在线 ok =
raw_input(prompt) 用户将是
问了这个问题,我会
也喜欢记录的答案。
使用如下函数:
def echoed_input(prompt):
response = raw_input(prompt)
sys.stdout.f.write(response)
return response
而不仅仅是在您的应用程序代码中使用raw_input(当然,这是专门为配合上面显示的tee 类而编写的)。
- 我读到了 Popen 和交流
并没有使用,因为它缓冲
内存中的数据。这里的输出量
很大,我需要关心
标准输出的标准错误
也是。你知道这是不是
可以用 Popen 和
沟通方式也一样?
communicate 没问题,只要您不获得比舒适地放入内存更多的输出(和标准错误),最多说几千兆字节,具体取决于您的机器类型'正在使用。
如果满足这个假设,只需将上面的代码重新编码为:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
so, se = p.communicate()
print(so)
retvalue = p.returncode
即,只需重定向子命令的 stderr 以混入其 stdout。
如果您确实需要担心千兆字节(或其他)会出现在您面前,那么
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
for line in p.stdout:
sys.stdout.write(p)
p.wait()
retvalue = p.returncode
(一次获取并发出一行)可能更可取(这取决于cmd 不期望从其标准输入中得到任何东西,当然......因为,如果它是期待什么,它不会得到它,问题开始变得具有挑战性;-)。