Python: subprocess.Popen().communicate() 将 SSH 命令的输出打印到标准输出而不是返回输出

Python: subprocess.Popen().communicate() prints output of an SSH command to stdout instead of returning the output

这是我的 python 终端的副本:

>> import subprocess
>> import shlex
>> host = 'myhost'
>> subprocess.Popen(shlex.split('ssh -o LogLevel=error -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes %s "hostname --short"' % (host))).communicate()
myhost
(None, None)

我希望输出为 ('myhost', None)。为什么输出没有存储在 communicate() 的 return 元组中?

您需要为 subprocess.Popen 调用提供 stdout 参数。例如:

>>> subprocess.Popen("ls", stdout=subprocess.PIPE).communicate()
(b'Vagrantfile\n', None)
>>>

命令的输出随后出现在您期望的位置。