Home > Software design >  Python script ends instead of restarting (os.execv)
Python script ends instead of restarting (os.execv)

Time:05-23

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)

CodePudding user response:

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.

CodePudding user response:

on windows, the os.exec* family of functions do not operate as they do on posixlikes -- instead of replacing the current process, they spawn a new one in the background and os._exit(1)

more on this here: https://github.com/python/cpython/issues/53394

on Windows, exec() does not really replace the current process. It creates a new process (with a new pid), and exits the current one.

you're probably best to either write a loop or use some sort of process manager

  • Related