How to Execute a Python Script from the Django Shell?
The Django shell is an interactive development and scripting environment that aids us in working with our Django project while experiencing it as if it were deployed already. It is most commonly used when one has to debug, test, or carry out one-time operations that require interaction with the Django models. However, such incidents can arise that would require us to run other Python code in addition to the ones we are working on.
This article will describe how to Run a Python script from the Django shell in a very quick and easy way.
Start the Django Shell
To run a Python script from the Django shell, we should set up our Django project first. When the project is finished, it is very easy to enter the Django shell. To start the Django shell, we can run the following command in the terminal:
python3 manage.py shell

The Django shell acts like a REPL terminal that gives us the ability of running command lines: running Python commands, ORM queries, making function calls, importing modules, etc.
Different ways to Execute Python Scripts from Django Shell
Once we have our Django Shell running, we can use it to perform our desired operations. We have a number of options to run our peace of code depending on our requirements. The most common methods are using the exec() function, the os.system() method and the subprocess module.
1. Using exec() Function:
With the exec() method, it is very simple to execute python code. This is handy in case of short codes that we intend to run across the Django setting:
with open('/path_to_script.py') as file:
exec(file.read())
Replace 'path_to_script.py' with your actual python code file path.
Let's say we have a script.py file that fetches all the Book from our Database. We are assuming that we have a Book model in our Django app.
script.py
from myapp.models import Book
print(Book.objects.all())
Run script.py from Django Shell
>>> with open('script.py') as f:
... exec(f.read())
...
Output

2. Using os.system:
If we prefer to execute the script as a separate process, we can consider using os.system() method
import os
os.system('python /path_to_script.py')
script.py
def multiply(a, b):
return a*b
print(multiply(2, 6))
Output:

Here, 0 denotes success and 6 is the output of the code.
But with this method, we cannot use Django Settings and run ORM Queries.
If we try to run ORM queries we get different errors. For e.g. when we try to run the following python code we get this error.
from myapp.models import Book
print(Book.objects.all())
Output:

Here, 1 represents error. The os tries to execute the code before the Django settings are being loaded.
2. Using subprocess:
The subprocess module is more convenient and powerful than os.system() in that it provides better control over the execution of the script:
import subprocess
result = subprocess.run(["python", "script.py"], capture_output=True, text=True)
print(result.stdout)
script.py
def multiply(a, b):
return a*b
print(multiply(2, 3))
Running Python Script from Django Shell Using Subprocess
>>> import subprocess
>>> result = subprocess.run(["python", "script.py"], capture_output=True, text=True)
>>> result
CompletedProcess(args=['python', 'script.py'], returncode=0, stdout='6\n', stderr='')
>>> print(result.stdout)
6
Output:

In this method also, we cannot use Django Settings and run ORM Queries.
We get errors something like this:

Conclusion
Running Python scripts directly from the Django shell is a powerful tool for developers who need to perform one-time operations, test specific code, or interact with Django models without deploying the project. By leveraging methods like exec()
, os.system()
, and the subprocess
module, we can execute external Python scripts with varying degrees of integration with our Django environment.
exec()
is best suited for executing small, self-contained scripts that can run within the Django shell's context, making it ideal for tasks that require access to Django models and settings.os.system()
andsubprocess
provide ways to execute scripts as separate processes. While these methods offer greater flexibility and control, they do not inherently integrate with Django's settings or ORM, leading to potential errors when trying to run ORM queries or access Django-specific configurations.
Understanding the strengths and limitations of each approach allows us to choose the most appropriate method based on our specific needs. Whether we are performing quick tests or running complex scripts, the Django shell provides a versatile environment that enhances the development and debugging process.