简体   繁体   English

在 Bash 中安排 Python 脚本?

[英]Schedule Python Script in Bash?

I am new to scheduling python scripts and need to start a script so it can run for a day or two.我是调度 python 脚本的新手,需要启动一个脚本,以便它可以运行一两天。 I am not allowed to use cron in my environment so am using this bash script.我不允许在我的环境中使用 cron,所以我使用这个 bash 脚本。 What is a simple test I can do to make sure the python file runs?我可以做哪些简单的测试来确保 python 文件运行? How would I know that my file ran?我怎么知道我的文件运行了? And also, if it throws an error, how can I make sure I am notified?而且,如果它抛出错误,我如何确保我收到通知? Any help would be appreciated.任何帮助,将不胜感激。

#!/usr/bin/bash

while true
do
    DATE="$(date +'%d')"
    MONTH="$(date +'%m')"
    YEAR="$(date +'%Y')"
    HOUR="$(date +'%H')"
    MINUTE="$(date +'%M')"
    if ([ "$DATE" = "27" ]) && [ "$HOUR" = "12" ] && [ "$MINUTE" = "30" ]
    then
                 /my_file.py
        sleep 24h
    fi
done

I've added a small snippet.我添加了一个小片段。

With the variable TRIGGER you can select your date when the script ( cron.sh or in your case course cron.py ) should be started the first time.使用变量TRIGGER您可以 select 您的脚本( cron.sh或在您的情况下为课程cron.py )应该第一次启动的日期。

WAIT determines the span between on run of the script ( cron ) and the next run (eg 5 minutes or 24 hours ) In my example I'm just waiting 5 minutes till the next run. WAIT确定脚本运行时 ( cron ) 和下一次运行之间的跨度(例如5 分钟24 小时) 在我的示例中,我只等待 5 分钟直到下一次运行。

Then we are checking if the Process ID of the started script cron.sh exists und react to this:然后我们检查启动脚本cron.sh的进程 ID 是否存在并对此做出反应:

  • PID not available and return value not zero: We need to restart the script. PID 不可用且返回值不为零:我们需要重新启动脚本。 There has been an error.出现错误。
  • PID not available and return value zero: Increment the trigger (waiting time). PID 不可用且返回值为零:增加触发器(等待时间)。 No error.没有错误。

Note that this is just an approach and very quick and dirty.请注意,这只是一种方法,非常快速和肮脏。 This should only demonstrate how this can be done.这应该只演示如何做到这一点。 You can take this and implement your own functionality now (notifications, logging, etc.)您现在可以使用它并实现自己的功能(通知、日志记录等)

Additionally:此外:

  • You can check, how often the cron-script has been started.您可以检查 cron 脚本的启动频率。 For example set a limit for restarting the cron.例如设置重启 cron 的限制。 If the cron-script fails multiple times in a row, you should deactive this and notify the User.如果 cron 脚本连续多次失败,您应该禁用它并通知用户。

  • If you want to be notified in case your script has failed multiple times, I personally like the option to send a mail: Send Mail via Terminal如果您想在脚本多次失败时收到通知,我个人喜欢发送邮件的选项: 通过终端发送邮件

  • Working with arrays and loops, it's possible to monitor more than one Python- or bash-script.使用 arrays 和循环,可以监控多个 Python 或 bash 脚本。

#!/usr/bin/bash

# Select how long between each run should be waited
WAIT="5 minutes"


process_started=false
tmp_pid=0

# For starting a detached process
startProcess() { 
    ./cron.sh &>/dev/null &
    tmp_pid=$(echo $!)
    process_started=true;
    return 0
}


# Make the current date to the staring point
TRIGGER=$(date +'%d-%m-%y-%H-%M') 
echo "Starting Point: $TRIGGER"

while true
do
  # Check for the trigger
  if [ $(date +'%d-%m-%y-%H-%M') = "$TRIGGER" ]; then
    # No process has been stared. Start the proces now
    if [ "$process_started" = false ]; then
      startProcess
      echo "Started script: "  $(date +'%d-%m-%y %H:%M:%S') " (PID $tmp_pid)"
    fi

    # Check for existence
    if ! kill -0 $tmp_pid > /dev/null 2>&1; then
      echo "No process found with pid $tmp_pid" >&2
      # Now, no process has been found. 
      # We can check of the exit code to determine
      # if the process has exited normally
      wait ${tmp_pid}
      if [ $? -eq 0 ]; then
       echo "Script exited normal: " $(date +'%d-%m-%y %H:%M:%S')" . Waiting another $WAIT"
        # Process has been exited normally.
        # Resetting the trigger.
        TRIGGER=$(date +'%d-%m-%y-%H-%M' -d "$WAIT")
        echo "New run in $WAIT: $TRIGGER"
      else
        echo "Script exited with an error"
        # Here. e. g. Start the script again
        startProcess
        echo "Retarted script: "  $(date +'%d-%m-%y %H:%M:%S') " (PID $tmp_pid)"
      fi
    fi
    sleep 1s
  fi
done

This of course also works with a python script.这当然也适用于 python 脚本。 Just change the function startProcess :只需更改 function startProcess

startProcess() { 
    ./cron.py &>/dev/null &
    tmp_pid=$(echo $!)
    process_started=true;
    return 0
}

and don't forget to include #!/usr/bin/env python3 in your cron.py file.并且不要忘记在您的cron.py文件中包含#!/usr/bin/env python3


With the following cron.sh使用以下cron.sh

x=1
while [ $x -le 5 ]
do
  x=$(( $x + 1 ))
  sleep 1s
done
exit 0

you will receive the output:您将收到 output:

Starting Point: 20-10-19-05-22
Started script:  20-10-19 05:22:36  (PID 86402)
No process found with pid 86402
Script exited normal:  20-10-19 05:22:46. Waiting another 5 minutes
New run in 5 minutes: 20-10-19-05-27

try, except clauses, catch errors you can use the smtp server at gmail and associated python library to send you an email you can run the whole thing in python if you want and forget about bash, make a while loop in python, you could write to local database or txt file to check if an instance is already running, so it won't run twice, a bash script can just constantly run it every few hours, and the script can manage itself here is a simple, local database I wrote, inspired by tinydb (which is also recommended) http://bobpizza2.pythonanywhere.com/ask?topic=43 try, except clauses, catch errors you can use the smtp server at gmail and associated python library to send you an email you can run the whole thing in python if you want and forget about bash, make a while loop in python, you could write到本地数据库或txt文件来检查一个实例是否已经在运行,所以它不会运行两次,一个bash脚本可以每隔几个小时不断运行一次,脚本可以自我管理这里是我写的一个简单的本地数据库,灵感来自 tinydb(也推荐) http://bobpizza2.pythonanywhere.com/ask?topic=43

dbe=db.database('test.db')
if dbe.search({'scripton':1}):
    sys.exit()
ide=dbe.insert_unq({'scripton':1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM