Is there any way to run .py script and if it occurs an error, to just restart it or continue. Right now if there's an error the script will stop running.
Asked
Active
Viewed 2.1k times
0
-
2that's why `try` `except` blocks present in python. – Avinash Raj Jul 18 '15 at 12:57
-
@opengl, if it did not work you did not use it correctly. Catch any possible exceptions and restart the script – Padraic Cunningham Jul 18 '15 at 13:09
-
1You may also find [`fuckit`](https://github.com/ajalt/fuckitpy) helpful – jonrsharpe Jul 18 '15 at 13:29
-
I would also recommend [logging.exception](https://docs.python.org/2/library/logging.html#logging.exception) , so you can figure out what the bleep happened later. – NightShadeQueen Jul 18 '15 at 15:18
1 Answers
1
You can catch errors and ignore them (if it makes sense). eg if the call foo.bar()
could cause an error use
try:
foo.bar()
except: #catch everything, should generally be avoided.
#what should happen when an error occurs
If you only want to ignore a certain type of error use (recommended) (python 2)
try:
foo.bar()
except <ERROR TO IGNORE>, e:
#what should happen when an error occurs
or (python 3)
try:
foo.bar()
except <ERROR TO IGNORE> as e:
#what should happen when an error occurs
See the Python documentation on handling exceptions for more information.

Holloway
- 6,412
- 1
- 26
- 33
-
2Note that the Python documentation warns: "The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way!" – tsroten Jul 18 '15 at 13:11
-
-
-
See https://stackoverflow.com/a/53575187/3140992 for quickly ignoring multiple commands, thanks to @jonrsharpe – citynorman Dec 01 '18 at 21:24