Search code examples
pythondjangounixamazon-ec2systemd

Crontab Launches Python Script but SystemD Does Not?


I can log into my AWS EC2 server via ssh and type:

cd /opt/myWebApp
sudo python3 /opt/myWebApp/manage.py myCronJob

...and it runs.

I can also launch the same script via crontab:

0 */6 * * * sudo python3 /opt/myWebApp/manage.py myCronJob --settings=server.settings.production 

But when I try to run it in SystemD, with .service file:

ExecStart='/usr/bin/python3.7' /opt/myWebApp/manage.py myCronJob --settings=server.settings.production

...I get:

ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

$PYTHONPATH and $VIRTUAL_ENV are empty. /opt/myWebApp/server_venv is empty as well. There's a python at /usr/bin/python3.7, but I'm referencing that in the SystemD .service file as noted above, and it's throwing that error.

What am I missing?


Solution

  • Solved it!

    ExecStart='/etc/alternatives/python3' ./manage.py myCronJob --settings=server.settings.production
    WorkingDirectory=/opt/myWebapp
    User=myUser
    

    The user ('myUser' in the above code) has access to Django.