簡體   English   中英

subprocess.CalledProcessError:返回非零退出狀態 1,而 os.system 不會引發任何錯誤

[英]subprocess.CalledProcessError: returned non-zero exit status 1, while os.system does not raise any error

給定以下命令:

newman run tests.postman_collection.json -e environment.json  --reporters testrail,json,html

提高:

RuntimeError: command 'newman run tests.postman_collection.json -e environment.json  --reporters testrail,json,html
' return with error (code 1): b'\nhttps://host.testrail.io/index.php?/runs/view/1234\n'

執行命令的py代碼:

        try:
            newmanCLI_output = subprocess.check_output(npmCLi, shell=True).decode().strip()
        except subprocess.CalledProcessError as e:
            raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

是的,我確實使用了 check_output 返回值。

output 是一個 url 來測試鐵路報告

那是os.system的一個錯誤特征; 它返回退出代碼以便您可以對其進行檢查,但如果出現問題則不會引發錯誤。

subprocess.check_output中的check意味着檢查命令是否成功,否則引發異常。 這通常是一件好事,因為您不希望進程在沒有警告的情況下在您的下面死掉。

但是如果你想禁用它,你可以使用subprocess.run解決它;

import shlex
result = subprocess.run(shlex.split(npmCLi), text=True, capture_output=True)
newmanCLI_output = result.stdout

避免shell=True並使用shlex.split來解析字符串的開關並不重要,但希望能夠演示如何正確地執行這些操作。

您仍然應該了解命令失敗的確切原因,以及忽略失敗是否安全。

暫無
暫無

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

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