run django manage.py command in cron

2.6k views Asked by At

I've written few management commands to run from cron. I'm using pipenv virtual environment

running from terminal directly is working great.

cd <project_path> pipenv run python manage.py <my_command>

I added same script as cron

cd /home/project_path && pipenv run python manage.py <my_command>

But this is giving error as

/bin/bash: pipenv: command not found

I also tried following command

 cd /home/project_path && python manage.py <my_command>

which is giving error as

File "manage.py", line 14
    ) from exc
         ^
SyntaxError: invalid syntax
2

There are 2 answers

0
Anuj TBE On BEST ANSWER

what solved my issue is setting absolute path to every module like

cd <project_path> && /root/.local/bin/pipenv run /home/user/.local/share/virtualenvs/myproject-IuTkL8w_/bin/python manage.py <my_command> 
1
Andrey Sobolev On

Put file run.py in root folder with settings.py file (NOTE! Your project structure may be different):

#!/usr/bin/env python
import os
import sys
import settings

p = os.path.abspath(os.path.join(os.path.dirname(__file__)))
sys.path.insert(0, '%s' % p)
sys.path.insert(0, '%s/apps' % p)
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
application = get_wsgi_application()

module_name = sys.argv[1]
exec('import %s' % module_name)
exec('%s.%s' % (module_name, ' '.join(sys.argv[2:])))

Then go to your app folder and make file cron.py with test() function

def test():
   print ('Hello world')

And final input next command to console:

python run.py your_app_name.cron "test()"