Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle subprocess.run() error/exception

How do I handle a subprocess.run() error in Python? For example, I want to run cd + UserInput with subprocess.run(). What if the user types in a directory name which does not exist? How do I handle this type of error?

like image 591
GameCube Avatar asked Oct 26 '25 14:10

GameCube


1 Answers

As @match has mentioned, you can't run cd as a subprocess, because cd isn't a program, it's a shell built-in command.

But if you're asking about any subprocess failures, besides cd:

try:
    subprocess.run(command_that_might_not_exist)  # like ['abcd']
except Exception:
    # handle the error
result = subprocess.run(command_that_might_fail)  # like ['ls', 'abcd/']
if result.returncode != 0:
    # handle the error
like image 68
Expurple Avatar answered Oct 29 '25 04:10

Expurple



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!