Linux下Python脚本崩溃自动重启实现及Shell脚本报错求助
Fixing Your Auto-Restart Shell Script for Python Programs
Hey there! Let's get that auto-restart script working properly so your Python program stays up and running. First, let's break down the issues in your original script, then walk through a corrected version.
What Was Wrong with the Original Script?
- Syntax Error: The line
if[["$LEN_COMMAND" -le "5"]]is missing critical spaces. In bash,if,[[, and the condition need spaces between them. It should beif [[ "$LEN_COMMAND" -le 5 ]](also, numbers don't need quotes here). - False Positives from
grep: When you runps aux | grep abc, thegrepcommand itself shows up in the process list. This can make your script think the program is running when it's not—we need to exclude thegrepprocess. - Unreliable Length Check: Using the length of the
psoutput to determine if the process is running is shaky. Output length can vary for unexpected reasons, so we should directly check if the process exists instead.
Corrected Shell Script
Here's a robust version of your script that fixes these issues:
#!/usr/bin/env bash # Check if the target Python process is running if ! ps aux | grep -E "abc.*def" | grep sudo | grep -v grep > /dev/null; then echo "$(date): Restarting the Python program..." # Replace this line with your actual program start command sudo /usr/bin/python3 /full/path/to/your/program.py & fi exit 0
Key Improvements Explained:
! ps aux ... > /dev/null: We redirect output to/dev/nullto keep things quiet. The!reverses the exit status—so if thepscommand doesn't find the process, we trigger the restart.grep -E "abc.*def": Uses extended regex to match processes that have both "abc" and "def" in their command line, which is more efficient than chaining multiplegrepcommands.grep -v grep: Excludes thegrepprocess itself from the results, eliminating false positives.- Absolute paths: Using
/usr/bin/python3instead of justpython3ensures Cron uses the correct Python executable (Cron has a limited environment).
Cron Setup Tips
Since Cron's smallest interval is 1 minute, here's how to set up checks every n seconds (example for 10 seconds):
Add these lines to your crontab (run crontab -e to edit):
* * * * * /full/path/to/your/my_prog.sh >> /var/log/program_restart.log 2>&1 * * * * * sleep 10; /full/path/to/your/my_prog.sh >> /var/log/program_restart.log 2>&1 * * * * * sleep 20; /full/path/to/your/my_prog.sh >> /var/log/program_restart.log 2>&1 * * * * * sleep 30; /full/path/to/your/my_prog.sh >> /var/log/program_restart.log 2>&1 * * * * * sleep 40; /full/path/to/your/my_prog.sh >> /var/log/program_restart.log 2>&1 * * * * * sleep 50; /full/path/to/your/my_prog.sh >> /var/log/program_restart.log 2>&1
- The
>> /var/log/program_restart.log 2>&1part logs all output (and errors) to a file, which is super helpful for debugging.
内容的提问来源于stack exchange,提问作者aja
相关产品推荐
相关产品推荐

