[問題] Popen印出訊息到stdout並存到變數

看板Python作者 (C語言)時間2周前 (2024/04/15 12:50), 2周前編輯推噓3(3010)
留言13則, 3人參與, 2周前最新討論串1/1
請問 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

04/15 12:56, 2周前 , 1F
應該是要改 stdin 把使用者輸入丟進去
04/15 12:56, 1F

04/15 13:07, 2周前 , 2F
我看懂你的意思了,你可以在 communicate 之前呼叫
04/15 13:07, 2F

04/15 13:07, 2周前 , 3F
process.stdout.readline() 把輸出行印出來
04/15 13:07, 3F

04/15 13:08, 2周前 , 4F
但子程序要輸出換行才行,也可以用 .read(5) 之類的
04/15 13:08, 4F

04/15 13:11, 2周前 , 5F
大概會像這樣
04/15 13:11, 5F

04/15 13:11, 2周前 , 6F
import subprocess as sp
04/15 13:11, 6F

04/15 13:11, 2周前 , 7F
p = sp.Popen(["python", "a.py"], stdout=sp.PIPE)
04/15 13:11, 7F

04/15 13:11, 2周前 , 8F
while p.poll() != 0:
04/15 13:11, 8F

04/15 13:11, 2周前 , 9F
print(p.stdout.read(1), flush=True)
04/15 13:11, 9F

04/15 13:11, 2周前 , 10F
res = p.communicate()
04/15 13:11, 10F

04/15 13:11, 2周前 , 11F
print(res)
04/15 13:11, 11F

04/15 14:04, 2周前 , 12F
communicate就會poll了 為何還要一個for loop
04/15 14:04, 12F

04/15 19:58, 2周前 , 13F
謝謝D大有方向了
04/15 19:58, 13F
文章代碼(AID): #1c7B7_vc (Python)
文章代碼(AID): #1c7B7_vc (Python)