1

I'm rather puzzled by why the code below doesn't print stdout and exit, instead it hangs (on windows). Any reason why?

import subprocess
from subprocess import Popen

def main():
    proc = Popen(
        'C:/Python33/python.exe',
        stderr=subprocess.STDOUT,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE
    )
    proc.stdin.write(b'exit()\r\n')
    proc.stdin.flush()
    print(proc.stdout.read(1))

if __name__=='__main__':
    main()

1 Answer 1

1

Replace the following:

proc.stdin.flush()

with:

proc.stdin.close()

Otherwise the subprocess python.exe will wait forever stdin to be closed.


Alternative: using communicate()

proc = Popen(...)
out, err = proc.communicate(b'exit()\r\n')
print(out)  # OR print(out[:1]) if you want only the first byte to be print.
Sign up to request clarification or add additional context in comments.

3 Comments

Nothing is printed then, python should at least write something to stdout.
@simonzack, Because you didn't give anything except exit() to the interpreter.
@simonzack, Try proc.stdin.write(b'print(123);exit()\r\n').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.