简体   繁体   English

如何重新启动 Python 脚本?

[英]How to restart a Python script?

In a program I am writing in python I need to completely restart the program if a variable becomes true, looking for a while I found this command:在我用python编写的程序中,如果变量变为真,我需要完全重新启动程序,寻找了一段时间我发现了这个命令:

while True:
    if reboot == True:
        os.execv(sys.argv[0], sys.argv)

When executed it returns the error [Errno 8] Exec format error .执行时返回错误[Errno 8] Exec format error I searched for further documentation on os.execv , but didn't find anything relevant, so my question is if anyone knows what I did wrong or knows a better way to restart a script (by restarting I mean completely re-running the script, as if it were been opened for the first time, so with all unassigned variables and no thread running).我在os.execv上搜索了更多文档,但没有找到任何相关内容,所以我的问题是是否有人知道我做错了什么或知道重新启动脚本的更好方法(通过重新启动我的意思是完全重新运行脚本,就好像它是第一次打开一样,所以所有未分配的变量都没有运行)。

There are multiple ways to achieve the same thing.有多种方法可以实现相同的目标。 Start by modifying the program to exit whenever the flag turns True .首先修改程序以在标志变为True时退出。 Then there are various options, each one with its advantages and disadvantages.然后有各种选择,每一种都有其优点和缺点。

Wrap it using a bash script.使用 bash 脚本包装它。

The script should handle exits and restart your program.该脚本应处理退出并重新启动您的程序。 A really basic version could be:一个非常基本的版本可能是:

#!/bin/bash
while :
do
    python program.py
    sleep 1
done

Start the program as a sub-process of another program.将程序作为另一个程序的子进程启动。

Start by wrapping your program's code to a function.首先将程序的代码包装到一个函数中。 Then your __main__ could look like this:然后你的__main__可能看起来像这样:

def program():
  ### Here is the code of your program
  ...

while True:
  from multiprocessing import Process
  process = Process(target=program)
  process.start()
  process.join()
  print("Restarting...")

This code is relatively basic, and it requires error handling to be implemented.这段代码比较基础,需要实现错误处理。

Use a process manager使用流程管理器

There are a lot of tools available that can monitor the process, run multiple processes in parallel and automatically restart stopped processes.有很多工具可以监控进程,并行运行多个进程并自动重启停止的进程。 It's worth having a look at PM2 or similar.值得一看PM2或类似的东西。

IMHO the third option (process manager) looks like the safest approach.恕我直言,第三个选项(流程管理器)看起来是最安全的方法。 The other approaches will have edge cases and require implementation from your side to handle edge cases.其他方法将有边缘情况,需要你方实施以处理边缘情况。

This has worked for me.这对我有用。 Please add the shebang at the top of your code and os.execv() as shown below请在代码和os.execv()顶部添加 shebang,如下所示

#!/usr/bin/env python3
import os
import sys

if __name__ == '__main__':
    while True:
        reboot = input('Enter:')
        if reboot == '1':
            sys.stdout.flush()
            os.execv(sys.executable, [sys.executable, __file__] + [sys.argv[0]])
        else:
            print('OLD')

I got the same "Exec Format Error", and I believe it is basically the same error you get when you simply type a python script name at the command prompt and expect it to execute.我得到了相同的“执行格式错误”,我相信这基本上与您在命令提示符下键入 python 脚本名称并期望它执行时遇到的错误基本相同。 On linux it won't work because a path is required, and the execv method is basically encountering the same error.在 linux 上它不起作用,因为需要路径,并且 execv 方法基本上遇到相同的错误。

You could add the pathname of your python compiler, and that error goes away, except that the name of your script then becomes a parameter and must be added to the argv list.您可以添加您的 python 编译器的路径名,并且该错误消失,除了您的脚本名称然后成为参数并且必须添加到 argv 列表中。 To avoid that, make your script independently executable by adding "#!/usr/bin/python3" to the top of the script AND chmod 755.为避免这种情况,请通过在脚本顶部添加“#!/usr/bin/python3”和 chmod 755 使您的脚本独立可执行。

This works for me:这对我有用:

#!/usr/bin/python3
# this script is called foo.py

import os
import sys
import time

if (len(sys.argv) >= 2):
    Arg1 = int(sys.argv[1])
else:
    sys.argv.append(None)
    Arg1 = 1

print(f"Arg1: {Arg1}")

sys.argv[1] = str(Arg1 + 1)
time.sleep(3)

os.execv("./foo.py", sys.argv) 

Output:输出:

Arg1: 1
Arg1: 2
Arg1: 3
.
.
.

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

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