<p>我想我可以共享一个不使用.poll()、.wait()或.communicate()的解决方案。几点:</p>
<ul>
<li>我使用<code>import codecs</code>,因为我的输出包含东亚UTF-8文本</li>
<li>我用<code>try:</code>捕获每一行,以筛选出损坏/无效的UTF-8文本</li>
<li>我使用<code>'\x0a'</code>强制Linux换行,而不考虑平台。</li>
<li>如果需要捕获stderr,请使用<code>for line in iter(subproc.stderr.readline, ''):</code></li>
<li>这种方法只在子程序创建输出时生成输出</li>
<li>在本例中,使用kw字典是过分的,但是演示了如何将**kwargs与子流程一起使用</li>
</ul>
<p>代码:</p>
<pre><code>import subprocess
import codecs
import os
kw = {
'bufsize': 0,
'executable': None,
'stdin': subprocess.PIPE,
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'preexec_fn': None,
'close_fds': False,
'shell': False,
'cwd': None,
'env': None,
'universal_newlines': False,
'startupinfo': None,
'creationflags': 0,
}
args = ['ls', '-lart']
kw['cwd'] = os.path.expanduser('~')
logfile = os.path.expanduser('~/stdout.txt')
stdlog = []
try:
subproc = subprocess.Popen(args,**kw)
except:
print 'Error loading subprocess. Check arguments and kwargs'
exit()
log = codecs.open(logfile,'w','utf-8')
log.write(': Starting log for: \"%s\"\x0a'%(' '.join(args)))
for line in iter(subproc.stdout.readline, ''):
try:
stdlog.append(line.rstrip().decode('utf-8'))
log.write(stdout[-1]+'\x0a')
print stdout[-1]
except:
pass
log.flush()
log.close()
</code></pre>