重新启动自我更新的python脚本

Ash*_*shy 37 python auto-update

我编写了一个脚本,通过从网站下载最新版本并覆盖正在运行的脚本来保持自己的最新状态.

我不确定在更新脚本后重新启动脚本的最佳方法是什么.

有任何想法吗?

我真的不想要一个单独的更新脚本.哦,它也必须在Linux/Windows上工作.

Ale*_*lli 27

在Linux或任何其他形式的unix中,os.execl和朋友是一个不错的选择 - 你只需要用上次执行的相同参数(或多或少)重新执行sys.executablesys.argv或者如果您需要通知您的下一个化身,它实际上是重新启动的任何变体.在Windows上,os.spawnl(和朋友)是你能做的最好的事情(尽管它会比os.execl和朋友在转换过程中花费更多的时间和内存).

  • 单行代码供将来参考:`os.execl(sys.executable,*([sys.executable] + sys.argv))` (25认同)

Jos*_*osh 16

CherryPy项目具有重新启动的代码.这里是他们是如何做到这一点:

    args = sys.argv[:]
    self.log('Re-spawning %s' % ' '.join(args))

    args.insert(0, sys.executable)
    if sys.platform == 'win32':
        args = ['"%s"' % arg for arg in args]

    os.chdir(_startup_cwd)
    os.execv(sys.executable, args)
Run Code Online (Sandbox Code Playgroud)

我在自己的代码中使用了这种技术,效果很好.(我没有在上面的窗口上做参数引用步骤,但如果参数可以包含空格或其他特殊字符,则可能是必要的.)


Jos*_*hua 5

我认为最好的解决方案应该是这样的:

你的正常程序:

...

# ... part that downloaded newest files and put it into the "newest" folder

from subprocess import Popen

Popen("/home/code/reloader.py", shell=True) # start reloader

exit("exit for updating all files")
Run Code Online (Sandbox Code Playgroud)

更新脚本:(例如:home/code/reloader.py)

from shutil import copy2, rmtree
from sys import exit

# maybie you could do this automatic:
copy2("/home/code/newest/file1.py", "/home/code/") # copy file
copy2("/home/code/newest/file2.py", "/home/code/")
copy2("/home/code/newest/file3.py", "/home/code/")
...

rmtree('/home/code/newest') # will delete the folder itself

Popen("/home/code/program.py", shell=True) # go back to your program

exit("exit to restart the true program")
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到您。