gpt4 book ai didi

python - 如何让脚本自动重启?

转载 作者:太空狗 更新时间:2023-10-30 00:23:23 58 4
gpt4 key购买 nike

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

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

现在,在 Python Shell 中,您必须按 Run 按钮,然后按“运行模块 (F5)”,或者只按键盘上的 F5 键.那是你第一次运行它。当程序结束时,您将返回到您的 Cheese.py 文件,然后按 F5 再次运行该程序。

大家都在吗?好的,那么我的问题是,如何让程序自动重启而无需您手动执行?

最佳答案

这取决于您所说的“自行重启”是什么意思。如果你只是想连续执行相同的代码,你可以将它包装在一个函数中,然后在 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.

这将不断重新运行脚本,提供从当前版本到新版本的命令行参数。可以在 Restarting a Python Script Within Itself 的帖子“Petr Zemek ”中找到关于此方法的更详细讨论。 .

一项 this article注释是:

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 using f.flush() or os.fsync(fd) before calling an exec*() function.

关于python - 如何让脚本自动重启?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36018401/

58 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com