Search code examples
pythonpython-3.xsubprocessstdoutpopen

Python - Unable to pass an opened file to Popen as stdout


I'm currently trying to redirect the standard output of the subprocess.Popen object to an opened file, so I followed the instructions found in many websites such as this.

However, the Popen.stdout is not correctly assigned for some reason

My code went as follows:

def foo(file):
    print(file)              # printA

    proc = subprocess.Popen('command, stdout=file) # i've tried with both shell=True/False
    print(proc)              # printB
    print(proc.stdout)       # printC
    return proc

def main():
    file = open('path', 'w')
    p = foo(file)
    print(p.stdout)          # printD   

The result is as of follows

printA: <_io.TextIOWrapper name='path' mode='w' encoding='UTF-8'>
printB: <subprocess.Popen object at 0x161966d0>
printC: None
printD: None

from what I read in the python doc here, the default for stdout is None if no PIPE is assigned to it. But since this here shows that apparently we can pass an opened file as the argument to stdout, I don't understand why my code doesn't work.

Please help.


Solution

  • I've run a simpler example and this is what I found:

    >>> p = subprocess.Popen('ls', stdout=open('moo','w'))
    >>> str(p.stdout)
    'None'
    

    However, file 'moo' does have the content of my current directory. After a useful hint from the user @eryksun (see comments below) and reading the source code, I've realized that p.stdout variable will be assigned only if PIPE is passed in the stdout parameter. In all other cases it will be set to None and this is exactly what the example above has demonstrated. The bottom line - everything works as expected.

    Also, please notice that if what the previous answer has suggested is correct you would get

    <type 'file'>
    

    in printA, so I don't think that the previous answer is correct.