如何在树莓派上用crontab每10分钟运行Python脚本?求助
Hey Jacob, let's walk through fixing your cron job issue step by step—looks like there's a small mistake in your schedule expression first off, plus a few other things to check to make sure everything runs smoothly.
1. Fix the Cron Schedule Expression
Your current line 10 * * * * python /home/pi/WeatherPi/production/getInfo.py only runs once per hour, at the 10th minute (e.g., 1:10, 2:10, etc.). To run the script every 10 minutes, you need to use the step operator */10 for the minutes field:
*/10 * * * * python /home/pi/WeatherPi/production/getInfo.py
This tells cron to execute the job every 10 minutes, starting from minute 0 (0,10,20,...50).
2. Verify the Python Interpreter Path
Cron uses a minimal environment, so it might not recognize the python alias you use in your regular shell. To find the full path to your Python interpreter:
- Run
which python(orwhich python3if you're using Python 3) in your terminal. You'll get something like/usr/bin/python3. - Replace
pythonin your cron line with this full path to avoid "command not found" errors. For example:*/10 * * * * /usr/bin/python3 /home/pi/WeatherPi/production/getInfo.py
3. Ensure Script Permissions & Shebang Line
- Make sure your script has executable permissions:
chmod +x /home/pi/WeatherPi/production/getInfo.py - Add a shebang line at the very top of your
getInfo.pyscript to specify the interpreter. This helps cron know exactly which Python version to use:#!/usr/bin/env python3
4. Check for Script & Path Issues
- First, test running the script manually using the exact command from your cron job to confirm it works:
If this fails, fix any errors in the script first (like missing dependencies, relative path issues—use absolute paths for files in your script instead of relative ones, since cron runs from your home directory by default)./usr/bin/python3 /home/pi/WeatherPi/production/getInfo.py
5. Debug with Cron Logs
On Raspberry Pi, cron logs are stored in /var/log/syslog. To check for errors related to your job:
grep CRON /var/log/syslog
Look for lines mentioning your script—they'll tell you if there was a permission error, missing file, or other issue.
Once you make these changes, save your crontab (:wq in nano if that's your editor) and wait a few minutes to see if the job runs as expected.
内容的提问来源于stack exchange,提问作者Jacob August

