将python脚本作为systemd服务运行

时间:2017-03-11 13:44:36

标签: python ubuntu systemd

我有一个python脚本systemd,它每2秒写一个文件。但是,当我想将此脚本作为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 文件 设计如下:

myScript.py

import time while True: with open("/home/pala/Documents/file.txt", "a") as myFile: myFile.write("--**--") time.sleep(2) 是:

 var self = this;

        self.selectedScreenNames = [
            {
                'name': 'one'
            },
            {
                'name': 'two'
            }
        ];


        $scope.remove = function(chip) {
            var index = self.selectedScreenNames.indexOf(chip);
            self.selectedScreenNames.splice(index, 0);
        };

        $scope.loadData = function () {
            console.log(self.selectedScreenNames) //This array still contains two values, after the remove has been called
        }

2 个答案:

答案 0 :(得分:2)

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

首先,在your_script.py的上方添加以下shebang

#!/usr/bin/env python

我正在按照以下说明创建自己的服务:

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

test.service

[Unit]
SourcePath=/etc/init.d/test
[Service]
ExecStart=/etc/init.d/test start
ExecStop=/etc/init.d/test stop

test.sh

#!/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

然后我为以上配置创建安装:

install.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"

最后,执行:

设置对your_script.py文件的访问权限:

$ chmod 755 <your_script.py>

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

$ sudo bash ./install.sh

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

然后启动您的服务:

$ sudo service test start

您可以检查其状态:

$ sudo service test status

[注意]:


答案 1 :(得分:0)

在myscript.service上添加工作目录可能有所帮助:

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

最好的问候 吉利安