看板 Python 關於我們 聯絡資訊
請問 subprocess.Popen 呼叫另一個程式的問題 需求是呼叫另一個程式將程式執行過程印出到畫面(stdout)之外 同時把執行過程存到變數裡做後續判斷 例子如下, hello.py 要求使用者輸入資料並印出,另一個程式 test.py呼叫 hello.py 想要儲存 hello.py 的執行過程,但是如果設定stdout=PIPE,執行過程就不會顯示提示 要使用者輸入資料 不知道該怎麼設定? hello.py if __name__=='__main__': name = input("please enter your name : ") print("hello, "+name) test.py def run_cmd(cmd): process = subprocess.Popen(cmd, universal_newlines=True, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() ret = process.returncode return ret, stdout, stderr def main(): retval, output, stderr = run_cmd("hello.py") print(f"\nResult:\n{output}") sys.exit(0) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.172.71.29 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1713156607.A.E66.html ※ 編輯: clanguage (218.172.71.29 臺灣), 04/15/2024 12:50:47 ※ 編輯: clanguage (218.172.71.29 臺灣), 04/15/2024 12:51:28
DaOppaiLoli: 應該是要改 stdin 把使用者輸入丟進去 04/15 12:56
DaOppaiLoli: 我看懂你的意思了,你可以在 communicate 之前呼叫 04/15 13:07
DaOppaiLoli: process.stdout.readline() 把輸出行印出來 04/15 13:07
DaOppaiLoli: 但子程序要輸出換行才行,也可以用 .read(5) 之類的 04/15 13:08
DaOppaiLoli: 大概會像這樣 04/15 13:11
DaOppaiLoli: import subprocess as sp 04/15 13:11
DaOppaiLoli: p = sp.Popen(["python", "a.py"], stdout=sp.PIPE) 04/15 13:11
DaOppaiLoli: while p.poll() != 0: 04/15 13:11
DaOppaiLoli: print(p.stdout.read(1), flush=True) 04/15 13:11
DaOppaiLoli: res = p.communicate() 04/15 13:11
DaOppaiLoli: print(res) 04/15 13:11
lycantrope: communicate就會poll了 為何還要一個for loop 04/15 14:04
clanguage: 謝謝D大有方向了 04/15 19:58