簡體   English   中英

將 python 腳本作為 systemd 服務運行

[英]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

[注意]:


也許它有助於在 myscript.service 添加一個工作目錄:

[Service]
(...)
WorkingDirectory=/home/pi/your_working_directory

最好的問候基利安

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM