<p>虽然<code>set_combine_stderr</code>确实将<code>stderr</code>转移到<code>stdout</code>流,但它是以混乱的顺序进行的,因此您无法得到您可能需要的结果,即,按写入顺序组合的行,就像在本地终端窗口中运行命令一样。相反,使用<code>get_pty</code>。这将导致服务器通过一个伪终端运行这些行,使它们按时间顺序排列。</p>
<p>这里有一个测试程序<code>outerr.py</code>,它在<code>stdout</code>和<code>stdin</code>上交替写入行。假设它位于llmps@meerkat2的主目录中。</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import sys
for x in xrange(1, 101):
(sys.stdout, sys.stderr)[x%2].write('This is line #%s, on std%s.\n' %
(x, ('out', 'err')[x%2]))
</code></pre>
<p>现在请尝试以下代码以远程运行它:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import paramiko
def connect():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('meerkat2', username='llmps', password='..')
return ssh
def runTest(ssh):
tran = ssh.get_transport()
chan = tran.open_session()
# chan.set_combine_stderr(True)
chan.get_pty()
f = chan.makefile()
chan.exec_command('./outerr.py')
print f.read(),
if __name__ == '__main__':
ssh = connect()
runTest(ssh)
ssh.close()
</code></pre>
<p>如果你运行上面的代码,你会看到100行按顺序排列。相反,如果您注释掉<code>chan.get_pty()</code>调用并取消注释<code>chan.set_combine_stderr(True)</code>调用,您将得到从运行到运行的<code>stdout</code>和<code>stderr</code>行的簇随机分布。</p>