argparse — Parser for command-line options, arguments and subcommands — Python 3.15.2 documentation
Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Command-line interface libraries » argparse — Parser for command-line options, arguments and subcommands | Theme | argparse — Parser for command-line options, arguments and subcommands ¶ Added in version 3.2. Вихідний код: Lib/argparse.py Примітка While argparse is the default recommended standard library module for implementing basic command line applications, authors with more exacting requirements for exactly how their command line applications behave may find it doesn’t provide the necessary level of control.
Refer to Choosing an argument parsing library for alternatives to consider when argparse doesn’t support behaviors that the application requires (such as entirely disabling support for interspersed options and positional arguments, or accepting option parameter values that start with - even when they correspond to another defined option). The argparse module makes it easy to write user-friendly command-line interfaces.
The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv . The argparse module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments. The argparse module’s support for command-line interfaces is built around an instance of argparse.ArgumentParser . It is a container for argument specifications and has options that apply to the parser as whole: parser = argparse .
ArgumentParser ( prog = 'ProgramName' , description = 'What the program does' , epilog = 'Text at the bottom of help' ) The ArgumentParser.add_argument() method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags: parser . add_argument ( 'filename' ) # positional argument parser . add_argument ( '-c' , '--count' ) # option that takes a value parser . add_argument ( '-v' , '--verbose' , action = 'store_true' ) # on/off flag The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object: args = parser . parse_args () print ( args . filename , args . count , args . verbose ) Примітка If you’re looking for a guide about how to upgrade optparse code to argparse , see Upgrading Optparse Code .
Об’єкти ArgumentParser ¶ class argparse. ArgumentParser ( prog = None , usage = None , description = None , epilog = None , parents = [] , formatter_class = argparse.HelpFormatter , prefix_chars = '-' , fromfile_prefix_chars = None , argument_default = None , conflict_handler = 'error' , add_help = True , allow_abbrev = True , exit_on_error = True , * , suggest_on_error = True , color = True ) ¶ Створіть новий об’єкт ArgumentParser .
Усі параметри слід передати як аргументи ключового слова. Кожен параметр має власний більш детальний опис нижче, але коротко вони: prog - The name of the program (default: generated from the __main__ module attributes and sys.argv[0] ) usage - рядок, що описує використання програми (за замовчуванням: генерується з аргументів, доданих до аналізатора) description - Text to display before the argument help (by default, no text) epilog - Text to display after the argument help (by default, no text) Parents - список об’єктів ArgumentParser , аргументи яких також мають бути включені formatter_class - клас для налаштування виведення довідки prefix_chars - набір символів, які є префіксом необов’язкових аргументів (за замовчуванням: „-„) fromfile_prefix_chars - набір символів, які є префіксами файлів, з яких слід читати додаткові аргументи (за замовчуванням: None ) argument_default - глобальне значення за замовчуванням для аргументів (за замовчуванням: None ) конфлікт_обробник - стратегія вирішення конфліктних опцій (зазвичай непотрібних) add_help - додає опцію -h/--help до аналізатора (за замовчуванням: True ) allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous (default: True ) exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True ) suggest_on_error - Enables suggestions for mistyped argument choices and subparser names (default: True ) color - Allow color output (default: True ) Змінено в версії 3.5: Додано параметр allow_abbrev .
Змінено в версії 3.8: У попередніх версіях allow_abbrev також вимикав групування коротких прапорців, таких як -vv , щоб означати -v -v . Змінено в версії 3.9: Додано параметр exit_on_error . Змінено в версії 3.14: suggest_on_error and color parameters were added. Змінено в версії 3.15: suggest_on_error default changed to True .
У наступних розділах описано, як використовується кожен із них. prog ¶ By default, ArgumentParser calculates the name of the program to display in help messages depending on the way the Python interpreter was run: The base name of sys.argv[0] if a file was passed as argument. The Python interpreter name followed by sys.argv[0] if a directory or a zipfile was passed as argument.
The Python interpreter name followed by -m followed by the module or package name if the -m option was used. This default is almost always desirable because it will make the help messages match the string that was used to invoke the program on the command line. However, to change this default behavior, another value can be supplied using the prog= argument to ArgumentParser : >>> parser = argparse . ArgumentParser ( prog = 'myprogram' ) >>> parser . print_help () usage: myprogram [-h] options: -h, --help show this help message and exit Note that the program name, whether determined from sys.argv[0] , from the __main__ module attributes or from the prog= argument, is available to help messages using the %(prog)s format specifier. >>> parser = argparse .
ArgumentParser ( prog = 'myprogram' ) >>> parser . add_argument ( '--foo' , help = 'foo of the %(prog)s program' ) >>> parser . print_help () usage: myprogram [-h] [--foo FOO] options: -h, --help show this help message and exit --foo FOO foo of the myprogram program Змінено в версії 3.14: The default prog value now reflects how __main__ was actually executed, rather than always being os.path.basename(sys.argv[0]) . usage ¶ By default, ArgumentParser calculates the usage message from the arguments it contains.
The default message can be overridden with the usage= keyword argument: >>> parser = argparse . ArgumentParser ( prog = 'PROG' , usage = ' %(prog)s [options]' ) >>> parser . add_argument ( '--foo' , nargs = '?' , help = 'foo help' ) >>> parser . add_argument ( 'bar' , nargs = '+' , help = 'bar help' ) >>> parser . print_help () usage: PROG [options] positional arguments: bar bar help options: -h, --help show this help message and exit --foo [FOO] foo help Специфікатор формату %(prog)s доступний для заповнення назви програми у ваших повідомленнях про використання.
When a custom usage
The rest of this page is on the live site.