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)
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)
然后我为上述配置创建一个安装:
#!/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)
[笔记]:
test、Your_User_Name、Your_path和your_script.py替换为上述脚本中的变量。