简体   繁体   English

Python popen python.exe

[英]Python popen python.exe

I'm rather puzzled by why the code below doesn't print stdout and exit, instead it hangs (on windows). 我很困惑为什么下面的代码不打印stdout并退出,而是挂起(在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()

Replace the following: 替换以下内容:

proc.stdin.flush()

with: 有:

proc.stdin.close()

Otherwise the subprocess python.exe will wait forever stdin to be closed. 否则,子python.exe将永远等待stdin关闭。


Alternative: using communicate() 备选:使用communication()

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.

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

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