在Python中,重复执行命令可以通过多种方式实现,以下是几种常见的方法:
1. 使用`while`循环和`time.sleep`:
import time
def execute_command(cmd, delay=60):
while True:
os.system(cmd)
time.sleep(delay)
if __name__ == "__main__":
cmd = sys.argv
execute_command(cmd)
2. 使用`for`循环:
for i in range(5):
重复运行的代码块
print("Hello, World!")
3. 使用递归函数:
def repeat_program(n):
if n > 0:
重复运行的代码块
print("Hello, World!")
repeat_program(n-1)
repeat_program(5)
4. 使用第三方库如`sched`设置定时器:
import sched
import time
scheduler = sched.scheduler(time.time, time.sleep)
def execute_command():
重复运行的代码块
print("Hello, World!")
scheduler.enter(1, 1, execute_command)
scheduler.run()
5. 使用`os.execvp`或`os.execl`重新启动当前Python进程:
import os
import sys
def restart():
try:
fun()
except EOFError as e:
print(e)
finally:
restart()