I have this python selenium script that after few minutes always throws some kind of error. Usually because chrome runs out of memory or there is some problem with proxy, but other errors also so its hard to catch them all. More simple for me would be solution, that the script would just restart itself every time there is an error. I know how to restart script, I just don't know how to tell python to do it when ANY error happens. Another solution would be something like "error ignore" because my script is already set to restart itself every x loops, but I cannot find anything like that for python.
1 Answer
You could catch every kind of error by just using a try/except around your whole code, and then restart the function in your except statement when any kind of error occurs. Here is a snippet of pseudo code:
def myfunc():
try:
do_something
except: # or catch one specific error with 'except AttributeError:'
myfunc()
3 Comments
scai
This leads to a recursion and will eventually reach the maximum recursion depth. Also it doesn't clean up anything that happens inside myfunc().
nostradamus
Agreed, it's nasty. But how would you solve the problem in an elegant way? In theory, automatically restarting a script after an exception occured should never be necessary in the first place.
scai
stackoverflow.com/a/33334183/1340631 has a solution without this recursion problem. It also closes opened files and connections on restart. Not sure if there are any other problems, though. And I agree with you that automatic restarts can be problematic, especially if there is no proper cleanup.
tryandexceptaround your whole code, and then loop the function in yourexceptstatement. Would that work for you?