Python脚本手动正常但Cron调度执行异常问题求助
Hey there! Let's break down why your cron-run Python script is acting up—chances are it's not actually a problem with /usr/lib64/python2.7/subprocess.py itself, but rather environment differences between your interactive shell and cron's minimal runtime environment. Here's how to diagnose and fix this:
1. Fix Command Paths in Subprocess Calls
Cron uses an extremely limited PATH (usually just /usr/bin:/bin), so any commands you call via subprocess in your script need absolute paths to work reliably. For example:
- Instead of
subprocess.run(["restic", "snapshots"]), use the full path torestic(find it withwhich resticin your interactive shell):subprocess.run(["/usr/local/bin/restic", "snapshots"])
2. Validate Environment Variables
Even though you're sourcing . /root/.restic-env;, cron's environment might still miss key variables present in your interactive shell. To compare:
- Add a temporary cron job to dump its environment:
* * * * * . /root/.restic-env; env > /tmp/cron_env.txt - Then run this in your root shell:
env > /tmp/shell_env.txt - Compare the two files with
diff /tmp/cron_env.txt /tmp/shell_env.txt—look for missing variables likeRESTIC_PASSWORD,PYTHONPATH, or extendedPATHentries that your script depends on.
3. Capture Error Output to Diagnose Exact Issues
Right now you don't know what specific error is occurring. Modify your cron job to log both stdout and stderr:
0 8 * * * . /root/.restic-env; /usr/bin/python /root/backup-mailer.py >> /tmp/backup_mailer.log 2>&1
After the cron runs, check /tmp/backup_mailer.log—it will show exactly where the script is failing (e.g., missing command, environment variable error, mail server connection issue).
4. Verify Python Runtime Context
Cron might be using a different Python context than your interactive shell, even with the full path. Add these lines to the top of your script to debug:
import sys print(f"Python Version: {sys.version}") print(f"Python Path: {sys.path}")
Compare the output in the log to what you see when running the script manually—if modules are missing, you may need to explicitly add their paths to sys.path in the script or set PYTHONPATH in your .restic-env file.
5. Check File Permissions and Absolute Paths
Make sure all files your script reads/writes (like config files, backup logs, or mail templates) are referenced with absolute paths. Cron doesn't use your interactive shell's working directory, so relative paths will break.
9 times out of 10, cron issues boil down to environment or path mismatches, not bugs in standard library modules like subprocess. Capturing that error log first will give you the exact clue you need to resolve the problem.
内容的提问来源于stack exchange,提问作者Jam3sn

