python如何重新开始程序_如何使Python程序自动重新启动

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

这将继续重新运行脚本,提供从当前版本到新版本的命令行参数。关于这个方法的更详细的讨论可以在Petr Zemek的文章“Restarting a Python Script Within Itself”中找到。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.


版权声明:本文为weixin_39842271原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。