在 CentOS 上启动 Python 服务,常见有几种方式,取决于你是临时跑一下、后台运行,还是当作系统服务长期运行。下面按常见场景给你说明。
python3 your_script.py
或(如果是 Python 2):
python your_script.py
⚠️ 关闭终端就会停止。
nohup python3 your_script.py > app.log 2>&1 &
查看进程:
ps -ef | grep your_script.py
停止:
kill -9 PID
sudo vi /etc/systemd/system/mypython.service
示例内容:
[Unit]
Description=My Python Service
After=network.target
[Service]
User=root
WorkingDirectory=/opt/myproject
ExecStart=/usr/bin/python3 /opt/myproject/your_script.py
Restart=always
[Install]
WantedBy=multi-user.target
注意:
python3路径用which python3查看WorkingDirectory是你的项目目录
sudo systemctl daemon-reload
sudo systemctl start mypython
sudo systemctl enable mypython # 开机自启
systemctl status mypython
journalctl -u mypython -f
systemctl stop mypython
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app
或用 systemd 管理 gunicorn。
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python app.py
python 但系统只有 python3firewall-cmd --add-port=8000/tcp --permanent
firewall-cmd --reload
如果你能告诉我:
我可以给你精准配置示例。