2013-12-21 49 views
1

为什么下面的代码不打印标准输出和退出,而是挂起(在窗口),我感到困惑。任何理由?Python popen python.exe

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

替换以下:

proc.stdin.flush() 

有:

proc.stdin.close() 

否则子python.exe会永远等待标准输入被关闭。


替代方法:使用通信()

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. 
+0

什么也没有打印然后,蟒至少应该写一些东西到stdout。 – simonzack

+0

@simonzack,因为除了'exit()'外,你没有给解释器。 – falsetru

+0

@simonzack,尝试'proc.stdin.write(b'print(123); exit()\ r \ n')'。 – falsetru