简体   繁体   English

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

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

Here's a copy of my python terminal: 这是我的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)

I would expect the output to be ('myhost', None) . 我希望输出是('myhost', None) Why isn't the output being stored in the return tuple for communicate()? 为什么输出未存储在return元组中,以便进行communication()?

You need to give the subprocess.Popen call a stdout argument. 您需要给subprocess.Popen调用一个stdout参数。 For example: 例如:

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

The output of the command then appears where you expect it. 命令的输出随即出现在您期望的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM