我想問一下,如果有一個例外的名字try: except:的錯誤No such file or directory。
例如:
try:
subprocess.run(["bash", my_path "start.sh"], shell=False)
except NoDirectory:
print('Error: This directory was not found. Please make sure the path is correct')
或者有沒有辦法subprocess.run從那里獲取錯誤代碼并從那里檢查它?
uj5u.com熱心網友回復:
使用stderr=subprocess.PIPE引數以便您可以檢查錯誤輸出。
import subprocess
r = subprocess.run(['bash', '/some/nonexistent/path.sh'], stderr=subprocess.PIPE)
if r.returncode:
if b'No such file or directory' in r.stderr:
print('That file was not found.')
uj5u.com熱心網友回復:
我無法bash在您的代碼中捕獲例外,正如它所寫的那樣。但是您可以嘗試以下代碼,即使它更長。您還可以發送一組命令,而不是一次發送一個命令:
注意- 在 Ubuntu 20.04 上測驗,使用 Python 3.8
commands = ("bash start.sh", "date",)
for c in commands:
p = subprocess.Popen(shlex.split(c), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, error = p.communicate()
rc = p.returncode
if rc != 0:
if error.find(b"No such file or directory"):
print("Error: This directory was not found. Please make sure the path is correct")
else:
print(error.decode().strip())
else:
print(output.decode().strip())
輸出:
Error: This directory was not found. Please make sure the path is correct
Wed 29 Dec 2021 06:10:15 PM EST
如果有人想出如何No such file or directory從bash使用subprocess.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398488.html
標籤:Python 猛击 子流程 试着抓 python-3.10
上一篇:如何流入wget?
