2017-02-11 128 views
0

我想與進程交互。 我可以開始這個過程並打印出前兩行(類似'成功啓動過程')。 現在我想發送一個新的命令到應該返回類似'命令完成'的過程,但沒有任何反應。Python與子進程交互

請幫幫我。

import subprocess 

def PrintAndPraseOutput(output, p): 
    print(output) 
    if 'sucessfully' in output: 
     p.stdin.write('command') 

cmd = ["./programm"] 
p = subprocess.Popen(cmd, universal_newlines=True, shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE) 
while p.poll() is None: 
    output = p.stdout.readline() 
    PrintAndPraseOutput(output, p) 

更新: 同樣的問題,後無產出「過程中成功啓動」

import subprocess 

def print_and_parse_output(output, p): 
    print(output) 
    if 'successfully' in output: 
     p.stdin.write('command\n') 


with subprocess.Popen(["./programm"], universal_newlines=True, shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE) as proc: 
    while proc.poll() is None: 
     output = proc.stdout.readline() 
     print_and_parse_output(output, proc) 
+0

這是一個有點難以調試這個不知道'programm'命令做什麼。你寫了嗎,還是可以修改它?也許它不會在其輸出結尾添加換行符,或者刷新「stdout」。 –

回答

0

你的I/O應行緩衝,所以PrintAndPraseOutput應在字符串末尾發送'\n'

順便說一句,你有幾個拼寫錯誤。該功能應命名爲print_and_parse_output以符合PEP-0008,並且「成功」具有2個c。

def print_and_parse_output(output, p): 
    print(output) 
    if 'successfully' in output: 
     p.stdin.write('command\n') 

當使用subprocess這樣是把它放在一個with語句是個好主意。從the subprocess.Popen` docs

POPEN對象支持經由with 語句上下文管理器:在退出,標準文件描述符被關閉,並且 過程中等待。

with Popen(["ifconfig"], stdout=PIPE) as proc: 
    log.write(proc.stdout.read()) 
+0

感謝您的回覆,我更新了我的問題。但仍然是同樣的問題 – seeberg