I want to execute a terminal command whenever I visit the index page in my Django app. I've done it outside of the Django app and it worked. Outside of my Django app I ran:
import subprocess
subprocess.run('python hello.py')
The hello.py file which contains a regular print statement print('Hello') and in the terminal from where I ran the command using the above script, it of course prints "Hello" like a charm.
My question is, is it possible to run something like below in my Django app?
def index(request):
subprocess.run('python manage.py process_tasks')
today = datetime.now()
schedule_time = datetime(year=today.year, month=today.month, day=today.day, hour=today.hour + 5,
minute=today.minute + 1,
tzinfo=pytz.UTC)
run_until = datetime(year=today.year, month=today.month, day=today.day, hour=today.hour + 5,
minute=today.minute + 1,
tzinfo=pytz.UTC)
print_hello(schedule=schedule_time, repeat=20, repeat_until=run_until)
return HttpResponse(f'Background task running...')
By including this command subprocess.run('python manage.py process_tasks') in the view function it will at least eliminate me opening another terminal to run python manage.py process_tasks to get the app to work in the background for me.
The app went to the page successfully but the background tasks aren't picking up and in the terminal it is saying ModuleNotFoundError: No module named 'background_task'. Here's the image with the error message for a better understanding. Thanks!
I found the problem... After narrowing down the error. It was trying to use the python.exe in the PATH and not the virtual environment.
subprocess.Popen('C:...project_name\\venv\\Scripts\\python.exe manage.py process_tasks')
That executed the task perfectly!