46

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

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

有任何想法吗?

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

4

8 回答 8

34

在 Linux 或任何其他形式的 unix 中,os.execl和朋友是一个不错的选择——您只需要使用上次执行的相同参数(或多或少)重新执行sys.executablesys.argv或如果您需要通知您的下一个化身它实际上是重新启动,则可以使用其任何变体。在 Windows 上,os.spawnl(和朋友)是你能做的最好的(虽然它会比 os.execl 和朋友在过渡期间暂时花费更多的时间和内存)。

于 2009-11-17T18:23:27.340 回答
20

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)

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

于 2011-04-22T18:54:14.297 回答
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")

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

我希望这能帮到您。

于 2009-11-17T21:20:42.817 回答
2

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

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

于 2009-11-17T18:23:32.587 回答
1

要额外支持带有 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()
于 2014-11-18T21:09:31.110 回答
0

主文件:

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”继续运行

于 2013-07-17T18:33:26.493 回答
0

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

def restart_program():
  print("Restarting Now...")
  os.system('your program here')
于 2020-12-02T15:43:44.300 回答
-1

您可以使用reload(module)重新加载模块。

于 2009-11-17T18:23:59.397 回答