BASH - crontab 始终在运行,除了 python 脚本



当我手动从 shell/var/tmp/server_always_alive.sh 运行此脚本时,没有问题。但是当我让它使用 crontab 运行时,即使所有的逻辑都是正确的,它也永远不会运行。

如何通过这个 crontab 使 python server.py 运行?

sun@sun-Inspiron-One-2320:~$ uname -a
Linux sun-Inspiron-One-2320 3.5.0-17-generic #28-Ubuntu SMP Tue Oct 9 19:31:23 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
/

var/tmp/server_always_alive.sh:

#!/bin/bash
echo "test 1"
echo "test 2"
# 58888 TCP port is server port of server.py, if its not running server.py has to execute auto
main=$(export DISPLAY=:0.0 && lsof -i tcp:58888 | grep LISTEN | awk '{print $2}')
if [ -z "$main" ]; then
        export DISPLAY=:0.0 && python /var/tmp/python/server.py &
        sleep 2
        break
fi
echo "test 3"
echo "all runs except python server.py"

crontab :

* * * * * /var/tmp/server_always_alive.sh &

>DISPLAY=:0.0表示您的 python"服务器"正在连接到 X 服务器。为什么?

Cron 不会有必要的 X "cookie"。,并且几乎可以肯定不会以与 X 服务器相同的用户身份运行。

编辑:我会相信你的话,你正在以正确的用户身份运行。

编辑:如果您确实需要从cron运行图形程序,请尝试

xhost +si:localuser:`whoami`

供替代锻炼参考。

第 1 步:将 python 脚本放在以下脚本上 = 将其保存在/var/tmp/main.sh

A) 非基于用户界面

#!/bin/sh
script='/my/python/script/is/here/ok.py'
/usr/bin/python $script &

B) GUI (GTK/TK 等)

#!/bin/sh
script='/my/python/script/is/here/ok.py'
export DISPLAY=:0.0 && /usr/bin/python $script &

第2步:现在使用以下方式在/etc/init.d/scriptname_what_ever_feed_i_name中制作一个文件(复制粘贴)

#! /bin/sh
PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/home/CHANGE _ ____ HERE ______ to the Step 1 file name
PIDFILE=/var/run/scriptname.pid
test -x $DAEMON || exit 0
. /lib/lsb/init-functions
case "$1" in
  start)
     log_daemon_msg "Starting feedparser"
     start_daemon -p $PIDFILE $DAEMON
     log_end_msg $?
   ;;
  stop)
     log_daemon_msg "Stopping feedparser"
     killproc -p $PIDFILE $DAEMON
     PID=`ps x |grep feed | head -1 | awk '{print $1}'`
     kill -9 $PID       
     log_end_msg $?
   ;;
  force-reload|restart)
     $0 stop
     $0 start
   ;;
  status)
     status_of_proc -p $PIDFILE $DAEMON atd && exit 0 || exit $?
   ;;
 *)
   echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload|status}"
   exit 1
  ;;
esac
exit 0

第 3 步:使其可执行chmod +x /etc/init.d/scriptname_what_ever_feed_i_namechmod -R 777 /etc/init.d/scriptname_what_ever_feed_i_name,以便作为任何用户,您无需 sudo 即可执行它。

第 4 步:例如:

/etc/init.d/scriptname_what_ever_feed_i_name restart

* * * * * /etc/init.d/scriptname_what_ever_feed_i_name restart

工作 - 而且更好/更安全。

ps aux | grep python
root      5026  0.5  0.3 170464 19336 pts/0    S    07:40   0:00 /usr/bin/python /var/tmp/python/server.py

现在你可以使用命令/etc/init.d/scriptname 手动启动或停止或停止 cron 等来启动和停止你的 python 脚本

最新更新