Running a Python script outside of Django

前端 未结 7 1912
后悔当初
后悔当初 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 04:08

    The easiest way to do this is to set up your script as a manage.py subcommand. It's quite easy to do:

    from django.core.management.base import NoArgsCommand, make_option
    
    class Command(NoArgsCommand):
    
        help = "Whatever you want to print here"
    
        option_list = NoArgsCommand.option_list + (
            make_option('--verbose', action='store_true'),
        )
    
        def handle_noargs(self, **options):
            ... call your script here ...
    

    Put this in a file, in any of your apps under management/commands/yourcommand.py (with empty __init__.py files in each) and now you can call your script with ./manage.py yourcommand.

    If you're using Django 1.10 or greater NoArgsCommand has been deprecated. Use BaseCommand instead. https://stackoverflow.com/a/45172236/6022521

提交回复
热议问题