Search code examples
pythonselenium-webdriverpython-ospython-exec

Python script ends instead of restarting (os.execv)


Whenever I run the following file (and main encounters the WebDriverException exception) my program ends instead of restarting. Would anyone know why that's happening? Any help would be greatly appreciated – thank you.

from uploadToBeatstars import main
from selenium.common.exceptions import WebDriverException

try:
    main()
except WebDriverException:
    print("Dumb target error happened. Restarting program.")
    from uploadToBeatstars import driver
    driver.close()
    import sys
    import os
    os.execv(sys.executable, ['python'] + sys.argv)

Solution

  • You don't need to respawn the interpreter after a failure in general, just retry in a loop:

    from uploadToBeatstars import main, driver
    from selenium.common.exceptions import WebDriverException
    
    while True:
        try:
            main()
        except WebDriverException:
            print("Dumb target error happened. Restarting program.")
            driver.close()  # Not sure if it is needed, can driver be alive after an exception?
            # Try again
        else:
            break  # Stop if no exception occurred.