knktc's Notes

python, cloud, linux...

0%

Run a Script Inside a Django Project

When working on a Django project, there are times when you need to process data directly against the project’s models and settings. In those situations, it is convenient to run a standalone script inside the Django environment instead of building a full command from scratch.

This post records a few ways to do that.

Django shell

Django’s built-in shell already loads the project environment, so a simple option is:

1
python manage.py shell < script.py

It is very simple, but it is not great when you want to pass arguments into the script, and it also does not work very naturally if your script is written around a main() function.

Custom management command

Another option is to create a small custom command. Here is a sample implementation I used recently. It can execute a target script file and pass through extra arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import os
import sys
import argparse
from django.core.management.base import BaseCommand


class Command(BaseCommand):
help = 'Run script in current project environment'

def add_arguments(self, parser):
parser.add_argument('script', type=str, nargs=argparse.REMAINDER,
help='script file path and args')

def handle(self, *args, **options):
args = options['script']
script_path = args[0]

if not os.path.isfile(script_path):
self.stderr.write(f'No such file: [{script_path}]')
sys.exit(1)

sys.argv = [script_path] + args[1:]

with open(script_path, 'r') as f:
exec(f.read(), {'__name__': '__main__'})

Put this file under any app’s management/commands directory and name it run_script.py.

After that, you can run a script like this:

1
python manage.py run_script your_script arg1 arg2 -v arg3

django-extensions

You can also use the built-in runscript feature from django-extensions.

Reference:

https://django-extensions-zh.readthedocs.io/zh_CN/latest/runscript.html

如果我的文字帮到了您,那么可不可以请我喝罐可乐?