1

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
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285

2 Answers2

0

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()"

  • It gives `ImportError: No module named settings`. Is there any use of import `settings` in the code? – Anuj TBE May 16 '18 at 12:26
0

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> 
Anuj TBE
  • 9,198
  • 27
  • 136
  • 285