Python 脚本结束而不是重新启动 (os.execv)

Python script ends instead of restarting (os.execv)

每当我 运行 以下文件(并且主要遇到 WebDriverException 异常)我的程序结束而不是重新启动。有谁知道为什么会这样吗?任何帮助将不胜感激 - 谢谢。

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)

一般情况下,您不需要在失败后重新生成解释器,只需循环重试即可:

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.

在 windows 上,os.exec* 系列函数不像它们在 posixlikes 上那样运行——它们不是替换当前进程,而是在后台生成一个新进程并且 os._exit(1)

这里有更多信息: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.

您最好要么编写一个循环,要么使用某种流程管理器