擅长:python、mysql、java
<p>你要的不是不可能的,但可能不是你真正想要的。</p>
<p>不要试图将屏幕输出保存到文件,只需将输出写入文件而不是屏幕。</p>
<p>像这样:</p>
<pre><code>with open('outfile.txt', 'w') as outfile:
print >>outfile, 'Data collected on:', input['header']['timestamp'].date()
</code></pre>
<p>只需将该<code>>>outfile</code>添加到所有打印语句中,并确保所有内容都缩进到该<code>with</code>语句下。</p>
<hr/>
<p>一般来说,最好使用字符串格式,而不是神奇的<code>print</code>逗号,这意味着您可以改用<code>write</code>函数。例如:</p>
<pre><code>outfile.write('Data collected on: {}'.format(input['header']['timestamp'].date()))
</code></pre>
<p>但如果<code>print</code>在格式化方面已经做了您想要做的事情,那么您现在就可以坚持使用它了。</p>
<hr/>
<p>如果你有其他人写的一些Python脚本(或者更糟的是,一个你没有源代码的编译C程序)却不能进行更改呢?然后,答案是将其包装在另一个脚本中,该脚本使用<a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">^{<cd6>}</a>模块捕获其输出。再说一次,你可能不想要,但如果你想要:</p>
<pre><code>output = subprocess.check_output([sys.executable, './otherscript.py'])
with open('outfile.txt', 'wb') as outfile:
outfile.write(output)
</code></pre>