这取决于您所说的“重新启动自身”。如果只想连续执行相同的代码,则可以将其包装在一个函数中,然后在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!
如果要 重新启动脚本,则可以再次执行该脚本,通过执行以下操作将当前进程替换为新进程:
#! /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.
这将连续重新运行脚本,提供从当前版本到新版本的命令行参数。这种方法的更详细的讨论可以在后“中找到重新开始一个python脚本在自身内”由彼得Zemek。
本文注意的一项是:
如果您使用上述解决方案,请记住,这些exec*()
函数会导致立即替换当前进程,而不会刷新打开的文件对象。因此,如果在重新启动脚本时有任何打开的文件,则应在调用 函数之前使用f.flush()
或刷新它们。os.fsync(fd)
exec*()