使用无限循环
while True:
运行的代码
这将导致程序无限循环,除非手动停止。
使用守护进程(daemon thread)
import threading
def daemon_thread_function():
while True:
运行的代码
daemon_thread = threading.Thread(target=daemon_thread_function)
daemon_thread.daemon = True
daemon_thread.start()
使用`nohup`命令
在命令行中,您可以使用`nohup`命令来运行Python脚本,这样即使您关闭终端窗口,脚本也会继续运行。
nohup python your_script.py &
使用`while`循环和`input()`函数
while True:
运行的代码
input("Press Enter to close program...\n")
程序将等待用户按下回车键后关闭。
使用系统服务
您可以将Python脚本设置为系统服务,这样即使系统重启或进入睡眠状态,脚本也会自动恢复运行。例如,使用`psutil`库来监控进程并设置为开机启动项。
使用事件循环
对于需要处理网络请求或其他I/O操作的脚本,您可以使用事件循环来保持程序运行,例如使用`asyncio`库。
请根据您的具体需求选择合适的方法。