Home > Software design >  Restart python program whenever it encounters an exception
Restart python program whenever it encounters an exception

Time:05-22

So I've got a selenium python script that occasionally runs into the following error at differing sections in my code:

Exception has occurred: WebDriverException
Message: unknown error: cannot determine loading status
from target frame detached

But when I encounter this error, if I re-run the program without changing anything, everything works again (so I know that it's either a problem with the website or the webdriver). In the meantime, I was wondering if there was a way to tell python to restart the program if a WebDriverException is encountered. Any help would be greatly appreciated, thank you.

CodePudding user response:

  1. You could simply use the os module to do this: os.execv(sys.argv[0], sys.argv)
  2. Use a main() function as a starting point for your program, and trigger that function again whenever you need to restart. Something like
def foo1():
    return
def foo2():
    try:
        ...
    except:
        main()
def main():
    foo1()
    foo2()
if __name__ == "main":
    main()

CodePudding user response:

You could try os.execv(), according to here, it enables a python script to be restarted, but you need to clean the buffers etc using this C-like function sys.stdout.flush()

try:
    <your block of code>
except WebDriverException:
    print(<Your Error>)

    import os
    import sys

    sys.stdout.flush()
    os.execv(sys.argv[0], sys.argv)

CodePudding user response:

If the error occurs because it does not find a certain tag, you could put a wait

element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )

or worst case

browser.implicitly_wait(5)

or

time.sleep(5)

which waits 5 seconds for the element to appear

  • Related