Sunraj Patel
Sunraj Patel

Reputation: 5

How to know and prevent an error with terminal commands from python?

Making a program which can open apps upon listening to commands. The app name is stored in variable 'a'. And then opened with the following line:

os.system("open /Applications/" + a + ".app")

But sometimes it is possible that 'a' does not exist on the system, say 'music' for which the console prints:

The file /Applications/music.app does not exist.

And the python code stops entirely.

How can I know that the console gave this error and prevent the program from stopping?

Upvotes: 0

Views: 149

Answers (2)

Gaëtan
Gaëtan

Reputation: 308

Maybe you could try to use the try/except commands to handle errors in python: https://docs.python.org/3/tutorial/errors.html.

Upvotes: 0

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

subprocess is more powerful than os.system, the stdout and stderr of subprocess can be ignored with subprocess

import subprocess
res=subprocess.run(["open", "/Applications/" + a + ".app"])
print(res.returncode)

use res.returncode to get the execute result(none zero value shows that the sub process has encountered errors).

Upvotes: 0

Related Questions