問題:怎么將Python腳本以systemd的方式運行?怎么把Python應用設置為自動啟動?
Step 1 編寫Python應用(最好以virtualenv的方式,將python和模塊安裝到Python應用目錄中),不管以模式或者其他方式運行,只要記下可以正常運行的命令行以及相應的目錄。
/data/xncd/python/xnbatchpersistence/venv/bin/python -m app.schedule.scheduler
Step 2 生成systemd服務文件
vi /lib/systemd/system/xnbatch.service
文件內(nèi)容如下:
[Unit]
Description=xnBatch Service
After=multi-user.target
Conflicts=getty@tty1.service
[Service]
Type=simple
WorkingDirectory=/data/xncd/python/xnbatchpersistence
ExecStart=/data/xncd/python/xnbatchpersistence/venv/bin/python -m app.schedule.scheduler
StandardInput=tty-force
[Install]
WantedBy=multi-user.target
Step 3 啟用服務
systemctl daemon-reload
systemctl enable xnbatch
systemctl start xnbatch
Step 4 檢測服務是否正常運行
systemctl status xnbatch
如果顯示為activate,則表示安裝成功:
systemctl status xnbatch
● xnbatch.service - xnBatch Service
Loaded: loaded (/usr/lib/systemd/system/xnbatch.service; enabled; vendor preset: disabled)
Active: active (running) since 二 2019-10-08 21:55:57 CST; 18min ago
Main PID: 13755 (python)
CGroup: /system.slice/xnbatch.service
└─13755 /data/xncd/python/xnbatchpersistence/venv/bin/python -m app.schedule.scheduler
10月 08 21:55:57 izuf66xttbby2as7xqznx2z systemd[1]: Started xnBatch Service.
Step 4 服務控制
停止服務
systemctl stop xbatch
啟動服務
systemctl start xnbatch
重啟服務
systemctl restart xnbatch