run python script from django

How to Run Python Script in Django Project

Sometimes you may need to execute a python script in Django shell or project. There are multiple ways to do this. In this article, we will look at the different ways to run python script in Django. This is very useful if you need to run python scripts for background tasks in your Django project. In many cases, web developers use this method to execute a python script in Django shell and run it as cron job to send automated messages and emails to their users.


How to Run Python Script in Django Project

Here are the different ways to run Python script, say, test.py in Django project. Most of the following commands use “./manage.py”. If they do not work for you, then please try the same commands with “sudo python ./manage.py” instead. This might happen because the Python PATH variable in your Linux system is not set.


1. Using shell

Navigate to the root folder of your Django project which contains manage.py file and run the python script using following command. We have assumed that manage.py and test.py are in same folders.

$ ./manage.py shell < test.py

If your python script is in a different folder, you need to provide the full path to your python script. In the following example, our python script is located at /home/ubuntu/test.py

$ ./manage.py shell < /home/ubuntu/test.py


2. Using execfile

You may also log into Django shell first with the following command.

$ ./manage.py shell

and then use execfile command to run the python script

>>> execfile('/home/ubuntu/test.py')

In python 3+, you will need to use exec command instead of using execfile.

>>> exec(open('/home/ubuntu/test.py').read())


3. Using manage.py

You may also use manage.py alone to run python scripts as shown below.

$ ./manage.py /home/ubuntu/test.py

In this article, we have seen three different ways to run python scripts from Django shell. Although it is not recommended to run python scripts from Django shell, this is a great way to run background tasks. This is because when you run python scripts from Django shell, it gives you access to all models, views and functions defined in your Django project.

Also read:

How to Disable CSRF Validation in Django
How to Enable CORS in Django Project
How to Combine Querysets in Django
How to Fix NoReverseMatch Error in Django
How to Convert PDF to Image/JPG in Linux