无限循环
使用`while True:`循环可以让代码块无限次执行,直到程序被外部方式(如用户中断)终止。
while True:
运行的代码
守护进程(Daemon Thread)
在Python中,可以通过创建守护线程来让程序在后台运行,即使主程序退出,守护线程也会继续运行。
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`命令可以让程序在后台运行,即使关闭终端窗口也不会停止。
nohup python your_script.py &
使用操作系统服务
在Linux系统中,可以使用`supervisor`来管理Python脚本作为系统服务运行。
安装supervisor
sudo apt-get install supervisor
创建配置文件
echo "[program:your_script]
directory=/path/to/your/script
command=python your_script.py
autostart=true
autorestart=true" > /etc/supervisor/conf.d/your_script.conf
更新并启动服务
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start your_script
使用`os.system`命令
在Windows系统中,可以使用`os.system`命令在后台运行Python脚本。
import os
os.system('nohup python your_script.py > output.log 2>&1 &')
使用`input()`函数
在代码的最后添加`input()`函数,可以让程序等待用户输入,从而防止程序自动退出。
input("Press Enter to close program...")
选择适合您需求的方法,可以确保Python脚本持续运行。