Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the methods for Django to execute a specified script

Shulou Source: shulou.com Published: 2022-06-01 18:54:55 11月01日 Update

This article mainly introduces the methods of Django to implement the specified script, the article is very detailed, has a certain reference value, interested friends must read it!

Django Shell

The shell that comes with Django actually loads various environment variables of the project, and there are a lot of descriptions on the Internet. Just run like this:

Python manage.py shell < script.py

Simplicity is very simple, but the deficiency is that it is not easy to add parameters, and it is not good to make the script run if you like to write main.

Custom Command

You can also customize a simple command to achieve the desired effect. The following is a recently written example that supports the execution of specified script files while adding more script execution parameters:

"" @ author:knktc@contact:me@knktc.com "" import osimport sysimport argparsefrom django.core.management.base import BaseCommandclass 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): # get args args = options ['script'] script_path = args [0] # check file existence if not os.path.isfile (script_path): self.stderr.write (f'No such file: [{script_path}]') sys.exit (1) # set args sys_argv = [script_path] + Args [1:] sys.argv = sys_argv # run with open (script_path 'r') as f: exec (f.read (), {'_ name__':'_ main__'})

Put this code in any app's management/commands directory, name it run_script.py, and then you can use this custom command once and for all.

After that, run the specified script with reference to the following command:

Python manage.py run_script your_script arg1 arg2-v arg3Django extensions

In addition, it can be implemented through the runscript built into the django-extensions package, which can be found in the documentation: https://django-extensions-zh.readthedocs.io/zh_CN/latest/runscript.html

The above is all the contents of the article "what are the ways for Django to execute a specified script?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Scripts methods references bad content parameters can be passed commands more articles once and for all code value interests variables and at the same time places guys buddies just Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information Shulou Tech Info NVidia Xiaomi