前台运行的程序影响了服务器的使用,但又希望该程序能一直运行,所以就考虑在后台跑这个PYTHON服务。
使用&在Linux/Mac终端后台运行
python your_script.py &程序会在后台运行
按回车返回终端
使用jobs查看后台任务
使用fg %1恢复到前台
后台运行
nohup python app.py > service.log 2>&1 &程序运行的时候会在工作台打印进程ID,也可以以命令行的方式查看:
ps aux | grep app.py可以用进程ID来关闭这个后台程序;
kill 9990 # 用你的实际进程ID也可以用pkill来关闭它;
pkill -f "python app.py"感觉这个方式比较适合开发过程中的调试。
使用systemd创建服务(Linux系统)
程序跑起来之后,可以考虑将它作为一个服务来运行。创建服务文件 /etc/systemd/system/myservice.service:
[Unit]
Description=My Python Service
[Service]
Type=simple
User=username
WorkingDirectory=/path/to/script
ExecStart=/usr/bin/python3 /path/to/script.py
Restart=always
[Install]
WantedBy=multi-user.target然后通过我们熟悉的systemctl来控制它:
sudo systemctl daemon-reload
sudo systemctl start myservice
sudo systemctl enable myservice # 开机自启

