Running a Python script outside of Django

前端 未结 7 1991
后悔当初
后悔当初 2021-01-30 03:22

I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).

Edi

7条回答
  •  天涯浪人
    2021-01-30 03:42

    I like to add the following command to my projects:

    myproject/management/commands/run-script.py:

    from django.core.management.base import BaseCommand, CommandError
    
    import imp
    import sys
    
    
    class Command(BaseCommand):
    
        help = """Run a non-django script with django settings."""
        args = " [...]"
    
        def handle(self, *args, **options):
            if len(args) == 0:
                raise CommandError("Path to script to run is required")
            sys.argv = list(args)
            imp.load_source("__main__", args[0])
    

    Then, I can run custom scripts, e.g:

    ./manage.py run-script /path/to/myscript.py --opt=value arg1 arg2
    

提交回复
热议问题