Linux启动停止守护程序目录调用shell/python脚本时出错
我刚刚熟悉Linux,由于目录问题,我似乎无法让Linux启动停止守护程序目录调用shell/python脚本时出错,python,linux,bash,shell,start-stop-daemon,Python,Linux,Bash,Shell,Start Stop Daemon,我刚刚熟悉Linux,由于目录问题,我似乎无法让启动-停止守护进程运行python脚本。在linux文件结构中,我有以下文件: ~/test.txt ~/test.py ~/test.sh 在从任何目录调用sudobash~/test.sh时,test.log将按照预期填充来自test.py的stdout。出于某些原因,启动以下启动-停止守护程序服务脚本将生成test.log,但不会使用stdout填充它: /etc/init.d/test 这是一个可以在启动-停止守护程序中解决的目录问题吗?
启动-停止守护进程运行python脚本。在linux文件结构中,我有以下文件:
~/test.txt
~/test.py
~/test.sh
在从任何目录调用sudobash~/test.sh
时,test.log将按照预期填充来自test.py的stdout。出于某些原因,启动以下启动-停止守护程序服务脚本将生成test.log,但不会使用stdout填充它:
/etc/init.d/test
这是一个可以在启动-停止守护程序中解决的目录问题吗?
或者,我愿意接受其他脚本服务方法,这些方法可以通过冷启动(即没有cron作业)来持久化。尝试使用绝对路径调用cd
,例如/home/alexjg/
,而不是~/
;之前它被破坏的原因是,在您的示例中,您使用的是sudo
,它保留了运行它的用户的主目录。但是,当您从init调用bash脚本时,它将使用root的主目录,该目录不包含test.py
创建文件是因为重定向仍然成功;但是,由于启动Python失败,因此没有输出。将cd~/
更改为绝对路径cd/home/alex
仍然会导致test.log为空。另外,行不是会回显“SHELL脚本成功”吗>/var/log/test.log
在调用test.py之前强制日志记录?@AlexJG您使用的是单个
,这意味着覆盖而不是附加。将
的两个实例替换为>
导致SHELL脚本成功写入test.log!但是,test.py中的print
语句仍然没有出现。请为python脚本提供“test.txt”的完整路径。你想把车停在哪里output@Tamar我想知道为什么脚本在没有test.py的显式路径的情况下无法运行,基本上为什么执行start-stop守护进程
的行为与调用bash~/test.sh
的行为不一样?按照我的理解,守护进程正在做同样的事情
THIS LINE IS A TEST
#!/usr/bin/python
import time
with open("test.txt") as f:
while True:
try:
print("Hello World")
print(f.readline())
time.sleep(2)
except KeyboardInterrupt:
f.close()
break
#!/bin/bash
echo "SHELL SCRIPT SUCCESS" > /var/log/test.log
cd ~/
./test.py > /var/log/test.log
#!/bin/sh
### BEGIN INIT INFO
# Provides: Python test script
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Prints out daemonized argument
# Description: Creates output of argument
### END INIT INFO
DAEMON_DIR=/home/alex
DAEMON=$DAEMON_DIR/test.sh
DAEMON_NAME=test
DAEMON_OPTS="hello"
DAEMON_USER=root
PYTHON=/usr/bin/python
PIDFILE=/var/run/$DAEMON_NAME.pid
. /lib/lsb/init-functions
do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon"
#start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --exec $PYTHON --startas $DAEMON
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --chuid $DAEMON_USER --startas /bin/bash /home/alex/test.sh
log_end_msg $?
}
do_stop () {
log_daemon_msg "Stopping system $DAEMON_NAME daemon"
start-stop-daemon --stop --pidfile $PIDFILE --retry 10
log_end_msg $?
}
case "$1" in
start|stop)
do_${1}
;;
restart|reload|force-reload)
do_stop
do_start
;;
status)
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
;;
*)
echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
exit 1
;;
esac
exit 0