I would like to ask if there is an exception name in try: except:
for the error No such file or directory
.
For example:
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')
Or is there a way to get an error code from subprocess.run
and to check it from there?
CodePudding user response:
I could not catch the bash
exception in your code, as it is written. But you can try the following code, even if it's longer. You can also send a tuple of commands, instead of one command at a time:
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())
Output:
Error: This directory was not found. Please make sure the path is correct
Wed 29 Dec 2021 06:10:15 PM EST
Very interested if someone figures out how to catch the No such file or directory
from bash
using subprocess
.
CodePudding user response:
Use the stderr=subprocess.PIPE
argument so you can examine the error output.
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.')