如何让 Python 程序自动重启
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36018401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Make a Python Program Automatically Restart Itself
提问by DavidEclipse
How do you make a python program automatically restart itself? So let's say there is a really simple program like:
你如何让python程序自动重启?因此,假设有一个非常简单的程序,例如:
var = input("Hi! I like cheese! Do you like cheese?").lower()
if var == "yes":
print("That's awesome!")
Now, in a Python Shell, you would have to press either the 'Run' button and then 'Run Module (F5)' or just the 'f5' button on your keyboard. That is the first time you run it. When the program ended, you would go back to your 'Cheese.py' file and then press 'f5' to run the program again. Everybody with me here? Ok, so my question is, how do you make the program restart itself automatically without you having to manually do it?
现在,在 Python Shell 中,您必须按“运行”按钮,然后按“运行模块 (F5)”或仅按键盘上的“f5”按钮。那是你第一次运行它。当程序结束时,您将返回到“Cheese.py”文件,然后按“f5”再次运行该程序。大家跟我一起来吗?好的,所以我的问题是,如何让程序自动重启而无需手动执行?
回答by Doug R.
It depends on what you mean by "restart itself." If you just want to continuously execute the same code, you can wrap it in a function, then call it from within a while True
loop, such as:
这取决于您所说的“重启本身”是什么意思。如果只想连续执行相同的代码,可以将其包装在一个函数中,然后从while True
循环中调用,例如:
>>> def like_cheese():
... var = input("Hi! I like cheese! Do you like cheese?").lower() # Corrected the call to `.lower`.
... if var == "yes":
... print("That's awesome!")
...
>>> while True:
... like_cheese()
...
Hi! I like cheese! Do you like cheese?yes
That's awesome!
Hi! I like cheese! Do you like cheese?yes
That's awesome!
If you want to actuallyrestart the script you can execute the script again, replacing the current process with the new one by doing the following:
如果您想真正重新启动脚本,您可以再次执行脚本,通过执行以下操作将当前进程替换为新进程:
#! /bin/env python3
import os
import sys
def like_cheese():
var = input("Hi! I like cheese! Do you like cheese?").lower()
if var == "yes":
print("That's awesome!")
if __name__ == '__main__':
like_cheese()
os.execv(__file__, sys.argv) # Run a new iteration of the current script, providing any command line args from the current iteration.
This will continuously re-run the script, providing the command line arguments from the current version to the new version. A more detailed discussion of this method can be found in the post "Restarting a Python Script Within Itself" by Petr Zemek.
这将不断重新运行脚本,提供从当前版本到新版本的命令行参数。这种方法的更详细的讨论可以在后“中找到重新开始一个python脚本在自身内”由彼得Zemek。
One item that this articlenotes is:
本文注意到的一项是:
If you use the solution above, please bear in mind that the
exec*()
functions cause the current process to be replaced immediately, without flushing opened file objects. Therefore, if you have any opened files at the time of restarting the script, you should flush them usingf.flush()
oros.fsync(fd)
before calling anexec*()
function.
如果您使用上述解决方案,请记住这些
exec*()
函数会立即替换当前进程, 而不会刷新打开的文件对象。因此,如果您在重新启动脚本时有任何打开的文件,您应该使用f.flush()
或os.fsync(fd)
在调用exec*()
函数之前刷新它们。
回答by user10081708
or you can try
或者你可以试试
$ chmod a+x "name".py
Then, you can run the script via
然后,您可以通过运行脚本
$ ./daemon.py
In such a situation, to restart the script, use the following code:
在这种情况下,要重新启动脚本,请使用以下代码:
os.execv(__file__, sys.argv)
Otherwise, when you run the script via
否则,当您通过以下方式运行脚本时
$ python daemon.py
use this code:
使用此代码:
os.execv(sys.executable, ['python'] + sys.argv)
Either way, do not forget to import the sys module
无论哪种方式,不要忘记导入 sys module
回答by Aaron Christiansen
You can wrap something in while True:
to make it execute repeatedly, as True
will always evaluate to True
, like this:
您可以将某些内容包装起来while True:
以使其重复执行,就像True
始终评估为True
一样,如下所示:
while True:
var = input("Hi! I like cheese! Do you like cheese?").lower() # <-- You had missed parentheses here
if var == "yes":
print("That's awesome!")
There's another issue with your code though; you haven't called lower
by putting parentheses after it.
不过,您的代码还有另一个问题;你没有lower
通过在它后面加上括号来调用。
回答by exbctel
I use terminal on my Mac to re-start some of my python scripts with the function below.
我在我的 Mac 上使用终端来重新启动我的一些 python 脚本和下面的函数。
import subprocess
def run_again(cmd):
subprocess.call(["bash", "-c", "source ~/.profile; " + cmd])
Note: Don't forget the space character after "profile;" or the function may fail silently!
注意:不要忘记“profile;”后面的空格字符 否则该功能可能会静默失败!
Then at the bottom of my script to be re-started:
然后在我的脚本底部重新启动:
if some_condition:
run_again("python my_script.py %s" % my_new_arguments)
For the original question about the cheese script:
对于关于奶酪脚本的原始问题:
if var != 'yes':
run_again("python my_cheese_script.py")