Why does Python raise ModuleNotFoundError from cron but not manually?
#1
I’ve been getting a weird error in my Python script where it says a module is not found, but only when I run it from a cron job. The import works fine when I execute it manually from the terminal. I’m not sure if it’s a path issue with the cron environment or something else.
Reply
#2
That sounds like the scheduled task environment isn't loading your venv or PATH. Try using the full path to Python and the script.
Reply
#3
In my case the import failed in cron but not in terminal because PYTHONPATH wasn't set for the job.
Reply
#4
I added a line to print sys.executable and the module search paths to a log, and it showed the env was different.
Reply
#5
I fixed it by calling /usr/bin/python3 /home/me/scripts/myscript.py, no venv; then I had to install dependencies system-wide.
Reply
#6
One time I thought it was a module issue, but the CWD in cron was different and a relative import broke.
Reply
#7
Another angle is to run the script from the cron directory with a proper cd or set WORKING_DIR.
Reply
#8
Do you have a virtualenv and a shebang line in the script?
Reply


[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Forum Jump: