2015-12-11 23 views
0

我使用subprocess從腳本中產生一個進程。我的subprocess需要JSON輸入並執行一些操作,並應將一些實時數據返回到主進程。我如何從subprocess做到這一點? 我正在嘗試這樣的事情。但它正在拋出一個錯誤。從python中的子進程接收返回數據

以下是5月主要工序 「main.py」

p = subprocess.Popen(['python','handler.py'], 
          stdin=subprocess.PIPE,stdout=subprocess.PIPE) 

p.communicate(JSONEncoder().encode(data)) 
while True: 
    out = process.stdout.read(1) 
    if out == '' and process.poll() != None: 
     break 
    if out != '': 
     sys.stdout.write(out) 
     sys.stdout.flush() 

下面是我subprocess 「handler.py」

if __name__ == '__main__' : 

    command = json.load(sys.stdin) 
    os.environ["PYTHONPATH"] = "../../" 

    if command["cmd"] == "archive" : 
     print "command recieved:",command["cmd"] 
     file_ids, count = archive(command["files"]) 
     sys.stdout.write(JSONEncoder().encode(file_ids)) 

但它拋出一個錯誤。

Traceback (most recent call last): 
    File "./core/main.py", line 46, in <module> 
    out = p.stdout.read(1) 
ValueError: I/O operation on closed file 

我在這裏做錯了什麼?

+0

'process'從哪裏來?你用'subprocessPopen'創建'p'。 –

回答

0

Popen.communicate()不會返回,直到進程終止並返回所有輸出。之後你無法讀取子進程的標準輸出。看看the .communicate() docs的頂部:

與進程交互:發送數據到stdin。 從stdout和 stderr中讀取數據,直到達到文件結束。 等待進程終止。如果你需要的代碼爲老年人

#!/usr/bin/env python3 
import json 
from subprocess import Popen, PIPE 

with Popen(command, stdin=PIPE, stdout=PIPE, universal_newline=True) as process: 
    with process.stdin as pipe: 
     pipe.write(json.dumps(data)) 
    for line in process.stdout: 
     print(line, end='') 
     process(line) 

:如果您要發送數據,然後逐行讀取文本輸出線,而孩子進程仍在運行重點是礦山

python版本或者您有緩衝問題,請參閱Python: read streaming input from subprocess.communicate()

如果你想要的是將數據傳遞到子進程和輸出打印到終端:

#!/usr/bin/env python3.5 
import json 
import subprocess 

subprocess.run(command, input=json.dumps(data).encode()) 

如果您的實際子進程是那麼Python腳本考慮導入它作爲一個模塊並運行相應的功能,請參閱Call python script with input with in a python script using subprocess

相關問題