0

我刚刚熟悉 Linux,但start-stop-daemon由于目录问题,我似乎无法运行 python 脚本。在 linux 文件结构中,我有以下文件:

~/test.txt

THIS LINE IS A TEST

~/test.py

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

~/test.sh

#!/bin/bash

echo "SHELL SCRIPT SUCCESS" > /var/log/test.log
cd ~/
./test.py > /var/log/test.log

sudo bash ~/test.sh从任何目录调用后, test.log将按预期填充来自test.py的标准输出。出于某种原因,启动以下 start-stop-daemon 服务脚本将生成一个test.log,但不会使用标准输出填充它:

/etc/init.d/test

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

这是可以在 中解决的目录问题start-stop-daemon吗?或者,我愿意接受其他可以通过冷启动持续存在的脚本服务方法(即没有 cron 作业)

4

1 回答 1

0

尝试cd使用绝对路径调用,例如,/home/alexjg/而不是~/; 它之前被破坏的原因是,在您的示例中,您正在使用sudo它保持运行它的用户的主目录。但是,当您从 init 调用 bash 脚本时,它将使用 root 的主目录,而不是不包含test.py.

文件被创建是因为重定向仍然成功;但是因为启动 Python 失败,所以没有输出。

于 2017-06-20T01:33:22.213 回答