如何让Python程序自动重启

Dav*_*pse 7 python

你如何让python程序自动重启?所以,假设有一个非常简单的程序,如:

    var = input("Hi! I like cheese! Do you like cheese?").lower()        
    if var == "yes":
        print("That's awesome!")
Run Code Online (Sandbox Code Playgroud)

现在,在Python Shell中,您必须按下"运行"按钮,然后按"运行模块(F5)"或键盘上的"f5"按钮.这是你第一次运行它.程序结束后,您将返回"Cheese.py"文件,然后按"f5"再次运行程序.和我在一起的每个人?好的,所以我的问题是,如何让程序自动重启,而不必手动完成?

Dou*_* R. 16

这取决于"重启自己"的意思.如果您只想连续执行相同的代码,可以将其包装在函数中,然后在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!
Run Code Online (Sandbox Code Playgroud)

如果要实际重新启动脚本,可以再次执行脚本,通过执行以下操作将当前进程替换为新进程:

#! /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.
Run Code Online (Sandbox Code Playgroud)

这将不断重新运行脚本,提供从当前版本到新版本的命令行参数.有关此方法的更详细讨论可以Petr Zemek的 " 在自己内部重新启动Python脚本 "一文中找到.

本文注意到的一个项目是:

如果您使用上述解决方案,请记住这些exec*() 函数会立即替换当前进程, 而不会刷新打开的文件对象.因此,如果在重新启动脚本时有任何打开的文件,则应在调用 函数之前f.flush()os.fsync(fd)之前刷新它们exec*().