Search code examples
pythonpython-2.7subprocessshlex

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:

>> 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). Why isn't the output being stored in the return tuple for communicate()?


Solution

  • You need to give the subprocess.Popen call a stdout argument. For example:

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

    The output of the command then appears where you expect it.