Django - where put argparse command to modify -h option?

纵然是瞬间 提交于 2019-12-24 09:40:03

问题


I would like to modify my help option in project I created. I put argparse in manage.py file, like this

parser = argparse.ArgumentParser(
    description="Some desc",
    formatter_class=argparse.RawTextHelpFormatter
)
args = parser.parse_args()
print(args)

if __name__ == "__main__":

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Reporter.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

but when I run python manage.py -h it works correctly (help shows), but when I run python manage.py runserver, I got: manage.py: error: unrecognized arguments: runserver How to solve this problem? I really don't know how to modify -h option.

Where should I put argparse code to get help in this django project? I know I can use own command, but it is important to me to get help after I make python manage.py -h

EDIT:

After help from comments, I created:

#!/usr/bin/env python


def help_parser():
    import argparse
    parser = argparse.ArgumentParser("Some desc",
        formatter_class=argparse.RawTextHelpFormatter
    )
    args = parser.parse_args()
    print(args[0])


def main():
    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Reporter.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)


if __name__ == "__main__":
    import sys

    if sys.argv[1] == '-h':
        help_parser()
    else:
        main()

回答1:


You probably ought not to introduce argparse into the picture here. Argparse and Argh are pretty usefull if you are writing a django CLI but not very helpful for adding a custom management command because the management api has most the requirements already built in albeit in a very different way.

For example, you can automatically get your command to show up when ./manage.py -h is executed merely by placing the .py file in the right location. For example if you create a file as

myapp/management/commands/custom.py

executing manage.py -h will reveal

[myapp]
    custom

You can customize it further by over setting the help variable.

class Command(BaseCommand):
    help = 'Custom help message here'

Now ./manage.py custom -h will reveal (among other things)

Closes the specified poll for voting



回答2:


Adding a new answer based on discussions.

You can keep your teacher happy by moving what's under the __main__ block to a separate function. So you have two functions in manage.py, the first one get's called when the argument is -h, the second one for everything else. Make sure that all the imports in manage.py are also moved to inside those functions rather than being at the top level.

Then

if __name__ == "__main__":
    import sys
    if len(sys.argv) == 2 and sys.argv[1] == '-h':
        help_parser()
    else:
        main()

Where main() contains the standard django manage.py code. Notice that you don't really need argparse here because now help_parser() only displays the help message for your app and doesn't have anything else to do.



来源:https://stackoverflow.com/questions/40887725/django-where-put-argparse-command-to-modify-h-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!