2013-12-21 47 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