Python /代码
>>> 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!
这应在Adhur 2和3号楼工作。
同样,引导次区的产出,不使用
retvalue = subprocess.check_call(cmd, shell=True)
允许<代码>cmd 输出到其正常的“标准产出”,但还是灰 gr和重新排放,具体如下:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
so, se = p.communicate()
print(so)
retvalue = p.returncode
假设你不关心标准操作员(仅为标准产出)和<代码>cmd的产出数量相当小(因为<代码>)。 如果这两种假设都与你完全想要的东西相对应,那么这种数据就很容易 t。
<>Edit:现在,在对这一答复的长篇评论中,欧佩组织已经澄清了这些细节:
- How to make the answers on the
questions stored in the output file
as well? For example on line ok =
raw_input(prompt) the user will be
asked for the question and I would
like to the answer logged as well.
职能如下:
def echoed_input(prompt):
response = raw_input(prompt)
sys.stdout.f.write(response)
return response
您的申请代码(当然,这是为了与上面所示的<代码>tee第一类合作而专门写成的)<代码>raw_input。
- I read about Popen and communicate
and didn t use since it buffers the
data in memory. Here amount of output
is big and I need to care about
standard-error with standard-output
as well. Do you know if this is
possible to handle with Popen and
communicate method as well?
don t获得的(和标准-error)产出超过记忆的舒适程度,即几兆字比照您重新使用的机器。
如果这一假设得到满足,仅将上述假设重新编号为:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
so, se = p.communicate()
print(so)
retvalue = p.returncode
i.e. 简单地将次游动物移至 st中。
如果您的指定官员不得不对你来的iga(或不管怎么说)感到担忧,那么
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<>> 代码>,但并不期望其标准input的任何内容,当然是因为如果该标准s<>> 它期望任何事情,不会得到,问题开始变得具有挑战性。