簡體   English   中英

如何使用子進程獲取輸出和返回代碼?

[英]How to get both the output and return code with subprocess?

我正在使用subprocess模塊來執行我的 C 程序,最后我想獲得程序返回的返回碼和輸出。 我試過這個:

result = subprocess.check_output(['src/main', '-n {0}'.format(n)], universal_newlines=True)

以上捕獲了程序的輸出,如果返回碼非零,它只會引發錯誤。 關鍵是我不想在非零錯誤代碼上引發錯誤,而是想在if語句中使用它,如果返回代碼非零,我想重新運行該過程。

現在,如果我將其更改為run ,並調用為:

result = subprocess.run(['src/main', '-n {0}'.format(n)])

然后,我可以執行result.returncode來獲取返回碼,但是當我執行result.stdout ,它會打印None 有沒有辦法同時獲得返回碼和實際輸出?

為了使用subprocess.run()捕獲輸出,您需要傳遞stdout=subprocess.PIPE 如果您還想捕獲 stderr,還可以通過stderr=subprocess.PIPE (或stderr=subprocess.STDOUT使 stderr 與result.stdout屬性中的 stdout 合並)。 例如:

result = subprocess.run(['src/main', '-n {0}'.format(n)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

或者,如果您使用的是 Python 3.7 或更高版本:

result = subprocess.run(['src/main', '-n {0}'.format(n)], capture_output=True)

您可能還想設置universal_newlines=True以將stdout 作為字符串而不是字節獲取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM