Python入门:如何通过docopt将initdb设置为True?
initdb to True with docopt? Hey there! Let's break this down step by step since you're new to docopt—it's totally normal to feel confused when first working with command-line argument parsers like this.
1. Understand docopt's core rule (the key fix!)
Docopt relies entirely on the docstring at the top of your script (the __doc__ variable) to define valid command-line arguments. If your docstring doesn't explicitly list initdb as a valid command/option, docopt will default it to False no matter what you do.
For example, your script needs a docstring that looks something like this to recognize initdb:
"""Your Database App Usage: your_script.py initdb your_script.py run Options: -h --help Show this help message. """
This tells docopt your script accepts two distinct commands: initdb (for database setup) and run (to start the app).
2. Run your script with the right terminal command
Once your docstring is set up correctly, you need to pass the initdb argument when launching your script from the terminal:
- If you just run
python your_script.pywithout any arguments, docopt can't match a valid command, so bothinitdbandrunstayFalse(which is what you're seeing now). - To flip
initdbtoTrue, run your script like this:python your_script.py initdb
3. Full working example to test
Here's a complete script you can copy-paste and experiment with:
"""Sample Database App Usage: app.py initdb app.py run Options: -h --help Show help information. """ from docopt import docopt if __name__ == '__main__': args = docopt(__doc__) print(args) # Will output {'initdb': True, 'run': False, '--help': False} when run with initdb if args['initdb']: print("Initializing database... Done!") elif args['run']: print("Starting application...") else: print("Please use either 'initdb' or 'run' as a command.")
When you run python app.py initdb, you'll see initdb set to True in the printed args, and the database initialization logic will execute.
内容的提问来源于stack exchange,提问作者Ahmed Ali

