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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值