将python脚本作为systemd服务运行

pal*_*323 5 python ubuntu systemd

我有一个python脚本myScript.py,每2秒写一个文件.但是,当我想将此脚本作为systemd服务运行时,服务可以工作但不能写入文件.

我创建了一个myscript.service文件/lib/systemd/system/ 并设计如下:

[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
Run Code Online (Sandbox Code Playgroud)

myScript.py是:

import time
while True:

    with open("/home/pala/Documents/file.txt", "a") as myFile:
        myFile.write("--**--")

    time.sleep(2)
Run Code Online (Sandbox Code Playgroud)

Ben*_*ari 1

service这是从您的代码创建的过程:

首先,在上面添加以下shebangyour_script.py

#!/usr/bin/env python
Run Code Online (Sandbox Code Playgroud)

我使用以下指令来创建自己的服务:

假设您的服务名称是“test”,然后创建以下文件:

测试服务

[Unit]
SourcePath=/etc/init.d/test
[Service]
ExecStart=/etc/init.d/test start
ExecStop=/etc/init.d/test stop
Run Code Online (Sandbox Code Playgroud)

测试文件

#!/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
Run Code Online (Sandbox Code Playgroud)

然后我为上述配置创建一个安装:

安装.sh

#!/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"
Run Code Online (Sandbox Code Playgroud)

最后,执行以下操作:

设置访问权限为your_script.py

$ chmod 755 <your_script.py>
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令安装服务:

$ sudo bash ./install.sh
Run Code Online (Sandbox Code Playgroud)

然后根据需要触发服务systemctl或重新启动计算机。

然后启动你的服务:

$ sudo service test start
Run Code Online (Sandbox Code Playgroud)

您可以检查其状态:

$ sudo service test status
Run Code Online (Sandbox Code Playgroud)

[笔记]:


  • 投票否决是因为: OP 中的问题与查找 python 无关,因此 env python 是多余的。在 systemd 中使用 init.d 风格的脚本比原始帖子的风格更糟糕。使用 cp 而不是 install 来安装可执行文件是不好的风格。对于脚本来说,这并不像对于实际编译的程序那么糟糕,但是使用 install 会更好。 (6认同)