"No such file or directory"对应的Exception名称?
Name of Exception corresponding to "No such file or directory"?
想问下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
获取错误代码并从那里进行检查?
我无法在您的代码中捕捉到 bash
异常,正如它所写的那样。但是你可以尝试下面的代码,即使它更长。您还可以发送一组命令,而不是一次发送一个命令:
NOTE - Tested on Ubuntu 20.04, using 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
如果有人想出如何使用 subprocess
从 bash
捕获 No such file or directory
,我将非常感兴趣。
使用 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.')
想问下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
获取错误代码并从那里进行检查?
我无法在您的代码中捕捉到 bash
异常,正如它所写的那样。但是你可以尝试下面的代码,即使它更长。您还可以发送一组命令,而不是一次发送一个命令:
NOTE - Tested on Ubuntu 20.04, using 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
如果有人想出如何使用 subprocess
从 bash
捕获 No such file or directory
,我将非常感兴趣。
使用 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.')