![](/img/trans.png)
[英]Running Python script as systemd service, connecting to InfluxDB results in ConnectionError
[英]running python script as a systemd service
我有一個 python 腳本myScript.py
,它每 2 秒寫入一個文件。 但是當我想將此腳本作為systemd
服務運行時,服務可以工作但不能寫入文件。
我在/lib/systemd/system/
上創建了一個myscript.service
文件,設計如下:
[Unit]
Description=My Script Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python /home/pala/PycharmProjects/myScript.py
[Install]
WantedBy=multi-user.target
而myScript.py
是:
import time
while True:
with open("/home/pala/Documents/file.txt", "a") as myFile:
myFile.write("--**--")
time.sleep(2)
service
的過程: 首先,在your_script.py
上面添加以下shebang :
#!/usr/bin/env python
我使用以下說明創建自己的服務:
假設您的服務名稱是"test" ,然后在下面創建文件:
[Unit]
SourcePath=/etc/init.d/test
[Service]
ExecStart=/etc/init.d/test start
ExecStop=/etc/init.d/test stop
#!/usr/bin/env bash
# Quick start-stop-daemon example, derived from Debian /etc/init.d/ssh
set -e
# Must be a valid filename
NAME=this_is_a_test
PIDFILE=/var/run/$NAME.pid
#This is the command to be run, give the full pathname
DAEMON=/home/Your_User_Name/Your_path/your_script.py
case "$1" in
start)
echo -n "Starting daemon: "$NAME
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_OPTS
echo "."
;;
stop)
echo -n "Stopping daemon: "$NAME
start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
echo "."
;;
restart)
echo -n "Restarting daemon: "$NAME
start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile $PIDFILE
start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_OPTS
echo "."
;;
*)
echo "Usage: "$1" {start|stop|restart}"
exit 1
esac
exit 0
然后我為上述配置創建一個安裝:
#!/usr/bin/env bash
echo "create a test service ..."
cp test.sh /etc/init.d/test
cp test.service /etc/systemd/system
chmod +x /etc/init.d/test
# sed -i "s/Your_User_Name/you_path/g" /etc/init.d/test
echo "created the test service"
設置對your_script.py
文件的訪問權限:
$ chmod 755 <your_script.py>
然后使用以下命令安裝服務:
$ sudo bash ./install.sh
然后使用systemctl
觸發服務或根據需要重新啟動您的機器。
然后啟動你的服務:
$ sudo service test start
您可以檢查其狀態:
$ sudo service test status
[注意]:
test
、 Your_User_Name
、 Your_path
和your_script.py
靜態變量替換為上述腳本中的變量。也許它有助於在 myscript.service 添加一個工作目錄:
[Service]
(...)
WorkingDirectory=/home/pi/your_working_directory
最好的問候基利安
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.