繁体   English   中英

"重新启动自更新 python 脚本"

[英]Restarting a self-updating python script

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

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

有任何想法吗?

我真的不想有一个单独的更新脚本。 哦,它也必须在 linux\/windows 上工作。

CherryPy 项目具有可自行重启的代码。 他们是这样做<\/a>的:

    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)

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

您的正常程序:

...

# ... 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")

更新脚本:(例如: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")

我希望这能帮到您。

最干净的解决方案是单独的更新脚本!

在其中运行您的程序,报告(退出时)有新版本可用。 这允许您的程序保存其所有数据,更新程序应用更新并运行新版本,然后加载保存的数据并继续。 对于用户来说,这可以是完全透明的,因为他们只运行运行真实程序的更新程序外壳。

pocoo 团队在 werkzueg 内部为他们的开发服务器提供了一个非常好的重新加载器。 此处<\/a>查看代码(位于文件底部)。

"

要额外支持带有 Python 的“-m”参数的脚本调用,可以使用以下命令(基于 Alex 的回答;Windows 版本):

os.spawnl(os.P_WAIT, sys.executable, *([sys.executable] +
    (sys.argv if __package__ is None else ["-m", __loader__.name] + sys.argv[1:])))
sys.exit()

主文件:

if __name__ == '__main__':

if os.path.isfile('__config.py'):
    print 'Development'
    push.update_server()
else:
    e = update.check()
    if not e: sys.exit()

更新文件:

def check():
    e = 1.....perform checks, if something needs updating, e=0;
    if not e:
        os.system("python main.pyw")
    return e

这是逻辑:

主程序调用更新函数

1)如果更新函数需要更新,它会更新并调用“main”的新实例

然后“main”的原始实例退出。

2)如果更新函数不需要更新,那么“main”继续运行

做一些事情不是更容易吗?非常简单,不需要额外的导入,并且与任何操作系统兼容,具体取决于您在 os.system 字段中输入的内容

def restart_program():
  print("Restarting Now...")
  os.system('your program here')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM