### Basic Configuration Pattern Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md A fundamental example of setting up an ArgumentParser and adding a required argument. This is the simplest way to start using configargparse. ```python parser = configargparse.ArgumentParser() parser.add_argument('--name', required=True) args = parser.parse_args() ``` -------------------------------- ### Basic ArgumentParser Setup Source: https://github.com/bw2/configargparse/blob/master/_autodocs/00-START-HERE.txt Demonstrates the basic setup of an ArgumentParser with default configuration files, a specific config file parser class (YAML), and an environment variable prefix. Use this for initializing your argument parser with common configuration sources. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['~/.config/app.yaml'], config_file_parser_class=configargparse.YAMLConfigFileParser, auto_env_var_prefix='APP_' ) parser.add_argument('--name', required=True) parser.add_argument('--debug', action='store_true') args = parser.parse_args() parser.print_values() # Show configuration sources ``` -------------------------------- ### Multi-line Documentation Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/help-formatters.md Configures an ArgumentParser with RawDescriptionHelpFormatter to handle multi-line program descriptions and argument help, preserving formatting. ```python import configargparse parser = configargparse.ArgumentParser( description="""MyApp - A sophisticated application Features: - Feature 1 - Feature 2 - Feature 3 Installation: pip install myapp""", formatter_class=configargparse.RawDescriptionHelpFormatter ) parser.add_argument('--type', default='auto', help='''Input type (auto, json, yaml, xml)''') ``` -------------------------------- ### Minimal Help with Defaults Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/help-formatters.md Sets up an ArgumentParser with ArgumentDefaultsHelpFormatter to display default values for arguments like retries, timeout, and verbose. ```python import configargparse parser = configargparse.ArgumentParser( formatter_class=configargparse.ArgumentDefaultsHelpFormatter, description='Simple tool' ) parser.add_argument('--retries', type=int, default=3) parser.add_argument('--timeout', type=int, default=30) parser.add_argument('--verbose', action='store_true') ``` -------------------------------- ### Install ConfigArgParse Source: https://github.com/bw2/configargparse/blob/master/README.md Use pip to install the ConfigArgParse library. This is the standard method for adding Python packages to your project. ```bash pip install ConfigArgParse ``` -------------------------------- ### YAMLConfigFileParser Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Shows how to use the YAMLConfigFileParser for parsing YAML formatted configuration files. This requires the PyYAML library to be installed. ```python import configargparse parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.YAMLConfigFileParser, default_config_files=['config.yaml'] ) parser.add_argument('--name', required=True) parser.add_argument('--servers', action='append') # config.yaml: # name: ProductionApp # servers: # - server1.example.com # - server2.example.com args = parser.parse_args() ``` -------------------------------- ### Tracking Configuration Sources Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md This example shows how to track the origin of configuration values. It uses `auto_env_var_prefix` to automatically map environment variables and prints the source of each parsed argument. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['app.conf'], auto_env_var_prefix='APP_' ) parser.add_argument('--name', required=True) parser.add_argument('--debug', action='store_true') parser.add_argument('--workers', type=int, default=4) args = parser.parse_args() # Show where each setting came from print("Configuration Sources:") print(parser.format_values()) ``` -------------------------------- ### Multi-Module Configuration Setup Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md Demonstrates how to manage configuration across multiple Python modules using a shared ArgumentParser instance. Each module can add its own arguments to the global parser. ```python import configargparse import database_module import cache_module # Get the global parser p = configargparse.get_argument_parser() # Add main module arguments p.add_argument('--config', is_config_file_arg=True) p.add_argument('--app-name', required=True) # Parse and show all settings args = p.parse_args() print(p.format_values()) ``` ```python import configargparse p = configargparse.get_argument_parser() p.add_argument('--db-host', env_var='DB_HOST', default='localhost') p.add_argument('--db-port', type=int, env_var='DB_PORT', default=5432) p.add_argument('--db-name', env_var='DB_NAME', required=True) ``` ```python import configargparse p = configargparse.get_argument_parser() p.add_argument('--redis-url', env_var='REDIS_URL') p.add_argument('--cache-ttl', type=int, default=3600) ``` -------------------------------- ### INI file format example Source: https://github.com/bw2/configargparse/blob/master/README.md Example of an INI file structure demonstrating comments, key-value pairs, quoted strings, boolean flags, integer types, list syntax, and multi-line text. ```ini # this is a comment ; also a comment [my_super_tool] # how to specify a key-value pair format-string: restructuredtext # white space are ignored, so name = value same as name=value # this is why you can quote strings quoted-string = '\thello\tmom... ' # how to set an arg which has action="store_true" warnings-as-errors = true # how to set an arg which has action="count" or type=int verbosity = 1 # how to specify a list arg (eg. arg which has action="append") repeatable-option = ["https://docs.python.org/3/objects.inv", "https://twistedmatrix.com/documents/current/api/objects.inv"] # how to specify a multiline text: multi-line-text = Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tortor odio, dignissim non ornare non, laoreet quis nunc. Maecenas quis dapibus leo, a pellentesque leo. ``` -------------------------------- ### Configure Help Message Display Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Use ArgumentParser with specific formatters and flags to control help message content. This example shows how to include configuration file syntax and environment variable hints in the help output. ```python parser = configargparse.ArgumentParser( formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter, add_config_file_help=True, # Show config file syntax add_env_var_help=True # Show env var hints ) parser.add_argument('--timeout', type=int, default=30, env_var='TIMEOUT') parser.add_argument('--servers', action='append', default=['localhost']) # Help will show: # --timeout TIMEOUT (default: 30) [env var: TIMEOUT] # --servers SERVERS (default: ['localhost']) ``` -------------------------------- ### Run script with config file and arguments Source: https://github.com/bw2/configargparse/blob/master/README.md Example of executing a Python script with configargparse, specifying a configuration file and additional command-line arguments. ```bash DBSNP_PATH=/data/dbsnp/variants_v2.vcf python config_test.py --my-config config.txt f1.vcf f2.vcf ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Demonstrates a typical YAML configuration structure with comments, lists, and nested values. This format is often used for application settings. ```yaml # Comments name: MyApp debug: true count: 42 # Lists servers: - server1.example.com - server2.example.com # Inline lists tags: [web, api, production] # Nested values (flattened to strings for argparse) settings: host: localhost port: 5432 ``` -------------------------------- ### Multi-Module Configuration Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/global-functions.md Illustrates how multiple modules can define their own command-line arguments using the shared singleton parser. All arguments are available in a single namespace after calling `parse_args()`. ```python # main.py import configargparse import database_module import api_module p = configargparse.get_argument_parser() p.add_argument('--config', is_config_file_arg=True) p.add_argument('--debug', action='store_true') options = p.parse_args() # database_module.py import configargparse p = configargparse.get_argument_parser() p.add_argument('--db-host', default='localhost') p.add_argument('--db-port', type=int, default=5432) # api_module.py import configargparse p = configargparse.get_argument_parser() p.add_argument('--api-port', type=int, default=8000) ``` -------------------------------- ### TOML file format example Source: https://github.com/bw2/configargparse/blob/master/README.md Example of a TOML file structure showing comments, section tables, key-value pairs, string quoting, boolean flags, and integer types. ```toml # this is a comment [tool.my-software] # TOML section table. # how to specify a key-value pair format-string = "restructuredtext" # strings must be quoted # how to set an arg which has action="store_true" warnings-as-errors = true # how to set an arg which has action="count" or type=int verbosity = 1 ``` -------------------------------- ### INI Configuration Example (ConfigparserConfigFileParser) Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Shows an INI file format with sections, multi-line values, and Python-like syntax for lists and dictionaries. This is compatible with Python's configparser. ```ini [section1] key = value # Multi-line values description = First line Second line Third line # Lists with Python syntax servers = ["server1", "server2"] # Dictionaries (as strings) settings = {'db': 'postgres', 'pool': 10} ``` -------------------------------- ### YAMLConfigFileParser syntax example Source: https://github.com/bw2/configargparse/blob/master/README.md Illustrates the subset of YAML syntax supported by YAMLConfigFileParser for setting configuration values, including booleans and lists. ```yaml # a comment name1: value name2: true # "True" and "true" are the same fruit: [apple, orange, lemon] indexes: [1, 12, 35, 40] colors: - green - red - blue ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Presents a TOML formatted configuration with nested tables, boolean values, integers, lists, and multi-line strings. TOML is known for its clear syntax. ```toml [tool.myapp] name = "MyApplication" debug = true port = 8000 # Lists servers = ["server1", "server2"] # Multi-line strings description = """ This is a longer multi-line description """ ``` -------------------------------- ### Priority Order Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Illustrates the order of precedence for configuration values: command-line arguments have the highest priority, followed by environment variables, config files, and finally default values. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['app.conf'], auto_env_var_prefix='APP_' ) parser.add_argument('--debug', action='store_true', default=False) # With app.conf containing: debug = true # And environment: APP_DEBUG=false # And command line: --debug # Result: debug = True (command-line wins) ``` -------------------------------- ### DefaultConfigFileParser Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Demonstrates using the DefaultConfigFileParser for a simplified INI/YAML hybrid format. This parser supports comments, various value formats, lists, and flags. ```python import configargparse parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.DefaultConfigFileParser ) parser.add_argument('--name') parser.add_argument('--debug', action='store_true') parser.add_argument('--tags', action='append') # Config file content: # name = MyApp # debug = true # tags = [web, api] args = parser.parse_args() ``` -------------------------------- ### Get Configuration Sources Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Retrieve a dictionary mapping settings to their source (e.g., command-line, config file, environment variable). ```python # Get configuration sources sources = parser.get_source_to_settings_dict() ``` -------------------------------- ### Example Usage of ArgumentDefaultsRawHelpFormatter Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/help-formatters.md Demonstrates how to use ArgumentDefaultsRawHelpFormatter with an ArgumentParser to display default values and preserve formatting in help messages for arguments. ```python import configargparse parser = configargparse.ArgumentParser( formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter ) parser.add_argument( '--output', default='/tmp/output.txt', help='Output file path' ) parser.add_argument( '--format', default='json', help='''Output format. Options: - json: JSON format - yaml: YAML format - xml: XML format''' ) args = parser.parse_args(['-h']) ``` -------------------------------- ### Customizing Help Message Formatting Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md This snippet illustrates how to customize the help message for your application using `description`, `epilog`, and `formatter_class`. It allows for detailed explanations and usage examples. ```python import configargparse parser = configargparse.ArgumentParser( description='''MyApp - A sophisticated application Features: - Feature A - Feature B - Feature C For more info, visit: https://example.com''', epilog='''Examples: Basic usage: %(prog)s --name MyApp With config file: %(prog)s -c config.yaml Generate config: %(prog)s --name Test -w config.yaml''', formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter ) parser.add_argument('-c', '--config', is_config_file_arg=True) parser.add_argument('-w', '--write-config', is_write_out_config_file_arg=True) parser.add_argument('--name', required=True, help='Application name') parser.add_argument('--workers', type=int, default=4, help='Number of worker threads') args = parser.parse_args(['-h']) ``` -------------------------------- ### Combined Defaults and Raw Formatting Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/help-formatters.md Uses ArgumentDefaultsRawHelpFormatter to display default values and preserve formatting for multi-line descriptions and argument help, including server addresses and log levels. ```python import configargparse parser = configargparse.ArgumentParser( description="""MyApp Configuration Config files: /etc/myapp/config.yaml ~/.myapp/config ./myapp.conf Environment Variables: MYAPP_* - Any argument can be set via env vars""", formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter ) parser.add_argument('--servers', action='append', default=['localhost'], help='''Server addresses Example: --servers server1 --servers server2''') parser.add_argument('--log-level', default='INFO', help='''Logging level DEBUG, INFO, WARNING, ERROR, CRITICAL''') ``` -------------------------------- ### Get Source to Settings Dictionary Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Returns an internal dictionary that tracks the origin of each setting (command line, environment variable, config file, or default). Use this to inspect where parsed values originated from. ```python parser = configargparse.ArgumentParser() parser.add_argument('--debug', env_var='DEBUG') args = parser.parse_args() sources = parser.get_source_to_settings_dict() # {'command_line': {'': (None, ['prog'])}, 'environment_variables': {'DEBUG': (action_obj, 'true')}} ``` -------------------------------- ### ConfigparserConfigFileParser Example Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Illustrates using the ConfigparserConfigFileParser to parse INI formatted configuration files with Python's configparser module. It supports multi-line values, list evaluation, and dictionary values. ```python import configargparse import yaml parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.ConfigparserConfigFileParser ) parser.add_argument('--system-settings', type=yaml.safe_load) parser.add_argument('--items', action='append') # config.ini: # [myapp] # system-settings: {'db': 'postgres', 'pool': 10} # items = ["a", "b", "c"] args = parser.parse_args() ``` -------------------------------- ### Get Possible Configuration Keys for an Action Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Retrieves a list of configuration file keys that can be used to set the value for a given argparse action. This is useful for understanding how to map settings in configuration files to command-line arguments. ```python parser = configargparse.ArgumentParser() action = parser.add_argument('--my-option') keys = parser.get_possible_config_keys(action) # keys = ['my-option', '--my-option'] ``` -------------------------------- ### YAMLConfigFileParser Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Parses configuration files in YAML format. Requires the PyYAML library to be installed. ```APIDOC ## Class: YAMLConfigFileParser ### Description Parses YAML format. Requires PyYAML (`pip install PyYAML`). ### Supported Syntax ```yaml # a comment name1: value name2: true # "True" and "true" are the same fruit: [apple, orange, lemon] indexes: [1, 12, 35, 40] colors: - green - red - blue ``` ### Example ```python import configargparse parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.YAMLConfigFileParser, default_config_files=['config.yaml'] ) parser.add_argument('--name', required=True) parser.add_argument('--servers', action='append') # config.yaml: # name: ProductionApp # servers: # - server1.example.com # - server2.example.com args = parser.parse_args() ``` ``` -------------------------------- ### Basic Argument Parsing with ConfigArgParse Source: https://github.com/bw2/configargparse/blob/master/README.md This script demonstrates how to set up an argument parser with ConfigArgParse, defining options that can be sourced from command-line arguments, config files, and environment variables. It also shows how to print parsed values and formatted help messages. ```python import configargparse p = configargparse.ArgParser(default_config_files=['/etc/app/conf.d/*.conf', '~/.my_settings']) p.add('-c', '--my-config', required=True, is_config_file=True, help='config file path') p.add('--genome', required=True, help='path to genome file') # this option can be set in a config file because it starts with '--' p.add('-v', help='verbose', action='store_true') p.add('-d', '--dbsnp', help='known variants .vcf', env_var='DBSNP_PATH') # this option can be set in a config file because it starts with '--' p.add('vcf', nargs='+', help='variant file(s)') options = p.parse_args() print(options) print("----------") print(p.format_help()) print("----------") print(p.format_values()) # useful for logging where different settings came from ``` -------------------------------- ### Get TOML Section Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Retrieves a specific section from parsed TOML data using a section name or path. ```python def get_toml_section(data, section): pass ``` -------------------------------- ### Configuration with Environment Variables Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Demonstrates using environment variables for configuration by setting an auto_env_var_prefix. Arguments will be looked up in environment variables prefixed with this value. ```python parser = configargparse.ArgumentParser(auto_env_var_prefix='APP_') parser.add_argument('--database-url', required=True) parser.add_argument('--api-key', required=True) args = parser.parse_args() # Set via: APP_DATABASE_URL=... APP_API_KEY=... ``` -------------------------------- ### Get or Create Global Parser Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Access a globally registered ArgumentParser instance by name. If it doesn't exist, it will be created. ```python # Get or create named parser parser = configargparse.get_argument_parser('myapp') ``` -------------------------------- ### ConfigFileParser get_syntax_description() Method Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md This abstract method should be implemented by subclasses to return a string describing the config file syntax for help messages. ```python def get_syntax_description(self): ``` -------------------------------- ### Print All Settings Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Display all parsed settings along with their origin (source). ```python # Show all settings and where they came from parser.print_values() ``` -------------------------------- ### Handle Unrecognized Arguments with parse_args Source: https://github.com/bw2/configargparse/blob/master/_autodocs/errors.md When using parse_args() in strict mode, unrecognized arguments will cause a SystemExit. This example shows how to trigger this behavior. ```python import configargparse parser = configargparse.ArgumentParser() parser.add_argument('--name') # This will call sys.exit(2) by default args = parser.parse_args(['--name', 'Alice', '--unknown', 'value']) ``` -------------------------------- ### Enhanced Help Formatting Source: https://github.com/bw2/configargparse/blob/master/_autodocs/README.md Sets up an ArgumentParser to use a formatter that includes configuration file syntax, environment variable names, and default values in the help output. This provides users with more context when using the command-line interface. ```python # Shows config file syntax, env var names, defaults parser = configargparse.ArgumentParser( formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter ) ``` -------------------------------- ### Initialize IniConfigParser (split_ml_text_to_list=False) Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Use IniConfigParser to parse INI files with mandatory sections. This example shows the default behavior where multiline strings are not converted to lists. ```python import configargparse parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.IniConfigParser(['tool:my_tool']) ) parser.add_argument('--format-string') parser.add_argument('--urls', action='append') # setup.cfg: # [tool:my_tool] # format-string = restructuredtext # urls = ["https://example.com/a", "https://example.com/b"] args = parser.parse_args() ``` -------------------------------- ### Typical Usage Pattern for ConfigArgParse Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Demonstrates the standard workflow for creating a parser, adding arguments with configuration file and environment variable support, and parsing arguments. Use this pattern to integrate configargparse into your application. ```python import configargparse # 1. Create parser parser = configargparse.ArgumentParser( default_config_files=['~/.myapp', '/etc/myapp/config'], auto_env_var_prefix='MYAPP_' ) # 2. Add config file path argument (optional) parser.add_argument('-c', '--config', is_config_file_arg=True) # 3. Add regular arguments parser.add_argument('--name', required=True) parser.add_argument('--debug', action='store_true') parser.add_argument('--servers', action='append') # 4. Add optional output argument (optional) parser.add_argument('-w', '--write-config', is_write_out_config_file_arg=True) # 5. Parse arguments args = parser.parse_args() # 6. Use results print(f"Name: {args.name}") print(f"Debug: {args.debug}") print("\nAll settings and sources:") parser.print_values() ``` -------------------------------- ### Standard Import Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Import the entire configargparse library using a standard alias. ```python # Standard import import configargparse ``` -------------------------------- ### Correct Usage of is_config_file_arg Source: https://github.com/bw2/configargparse/blob/master/_autodocs/errors.md Demonstrates the correct way to use `is_config_file_arg=True` by setting the action to 'store'. Using other actions like 'append' will result in a ValueError. ```python import configargparse parser = configargparse.ArgumentParser() # CORRECT parser.add_argument('-c', '--config', is_config_file_arg=True, action='store') ``` -------------------------------- ### Configuration with Default Config File Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Shows how to specify default configuration files and the parser class to use for loading them. The '-c' or '--config' argument allows overriding the default config file path. ```python parser = configargparse.ArgumentParser( default_config_files=['~/.config/app.yaml'], config_file_parser_class=configargparse.YAMLConfigFileParser ) parser.add_argument('-c', '--config', is_config_file_arg=True) parser.add_argument('--name', required=True) args = parser.parse_args() ``` -------------------------------- ### Config file syntax for DefaultConfigFileParser Source: https://github.com/bw2/configargparse/blob/master/README.md Demonstrates the various ways to specify key-value pairs, boolean flags, and list arguments within a configuration file using the DefaultConfigFileParser. ```yaml # this is a comment ; this is also a comment (.ini style) --- # lines that start with --- are ignored (yaml style) ------------------- [section] # .ini-style section names are treated as comments # how to specify a key-value pair (all of these are equivalent): name value # key is case sensitive: "Name" isn't "name" name = value # (.ini style) (white space is ignored, so name = value same as name=value) name: value # (yaml style) --name value # (argparse style) # how to set a flag arg (eg. arg which has action="store_true") --name name name = True # "True" and "true" are the same # how to specify a list arg (eg. arg which has action="append") fruit = [apple, orange, lemon] indexes = [1, 12, 35 , 40] ``` -------------------------------- ### Basic ArgumentParser Initialization Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Initializes an ArgumentParser with default configuration file paths. ```python import configargparse # Basic usage parser = configargparse.ArgumentParser( default_config_files=['/etc/app.conf', '~/.app_config'] ) ``` -------------------------------- ### Get Global ArgumentParser Singleton Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/global-functions.md Retrieves a global ArgumentParser singleton by name. Creates it if it doesn't exist. Useful for sharing a parser instance across different modules. ```python import configargparse # In main.py p = configargparse.get_argument_parser('main') p.add_argument('-x', help='Main setting') # In utils.py import configargparse p = configargparse.get_argument_parser('main') p.add_argument('--utils-setting', help='Util setting') # Both reference the same parser instance options = p.parse_args() ``` -------------------------------- ### format_help() Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Generates a formatted help message that includes standard argparse help along with configargparse extensions for configuration file syntax and environment variables. ```APIDOC ## format_help() ### Description Return a formatted help message including standard argparse help plus configargparse extensions (config file syntax, environment variables). ### Returns `str` - The formatted help message. ### Example ```python parser = configargparse.ArgumentParser( default_config_files=['app.conf'], auto_env_var_prefix='APP_' ) parser.add_argument('--verbose', action='store_true') parser.add_argument('--output') print(parser.format_help()) # Includes sections for both argparse help and config file syntax ``` ``` -------------------------------- ### Basic Config File Support with INI Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md Enables loading configuration from default INI files and allows specifying a config file path via command line. Supports adding help for config file options. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['~/.config/app.conf'], add_config_file_help=True ) # Allow specifying config file on command line parser.add_argument('-c', '--config', is_config_file_arg=True, help='Config file path') parser.add_argument('--database', required=True, help='Database URL') parser.add_argument('--timeout', type=int, default=30, help='Timeout in seconds') parser.add_argument('--debug', action='store_true', help='Enable debug mode') args = parser.parse_args() ``` ```ini # Application configuration database = postgresql://localhost/myapp timeout = 60 debug = true ``` ```bash # Use default config python app.py # Override config python app.py -c /etc/app.conf --timeout 120 # Show help (includes config syntax) python app.py -h ``` -------------------------------- ### Correct Usage of is_write_out_config_file_arg Source: https://github.com/bw2/configargparse/blob/master/_autodocs/errors.md Shows the correct usage of `is_write_out_config_file_arg=True` by ensuring the action is set to 'store'. Incorrect actions will lead to a ValueError. ```python import configargparse parser = configargparse.ArgumentParser() # CORRECT parser.add_argument('-w', '--write-config', is_write_out_config_file_arg=True, action='store') ``` -------------------------------- ### Basic Argument Parsing in Python Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md Demonstrates how to create a parser, add required and optional arguments, and parse them from the command line. Use this for simple command-line tools. ```python import configargparse # Create parser parser = configargparse.ArgumentParser(description='Simple tool') # Add arguments parser.add_argument('--name', required=True, help='Your name') parser.add_argument('--age', type=int, help='Your age') parser.add_argument('--verbose', action='store_true', help='Verbose output') # Parse arguments args = parser.parse_args() print(f"Name: {args.name}") print(f"Age: {args.age}") print(f"Verbose: {args.verbose}") ``` ```bash python app.py --name Alice --age 30 --verbose ``` -------------------------------- ### Format Parsed Argument Values and Sources Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Use `format_values` to get a string representation of all parsed arguments, indicating their source (command line, environment variable, config file, or default). This is helpful for debugging and understanding how arguments were resolved. ```python def format_values(self): ``` ```python parser = configargparse.ArgumentParser(default_config_files=['app.conf']) parser.add_argument('--debug', env_var='DEBUG') args = parser.parse_args() print(parser.format_values()) # Output: # Command Line Args: --debug true # Environment Variables: # Config File (app.conf): # Defaults: ``` -------------------------------- ### Create Basic ArgumentParser Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Instantiate a basic ArgumentParser object. No specific configuration is applied. ```python import configargparse # Basic parser = configargparse.ArgumentParser() ``` -------------------------------- ### Combined Config Files and Environment Variables Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md Demonstrates how configargparse merges settings from command-line arguments, environment variables, and config files. Shows the priority order for resolving settings. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['/etc/app.conf', '~/.app_config'], auto_env_var_prefix='APP_' ) parser.add_argument('-c', '--config', is_config_file_arg=True) parser.add_argument('--name', required=True) parser.add_argument('--debug', action='store_true') parser.add_argument('--threads', type=int, default=4) args = parser.parse_args() ``` ```text Priority (highest to lowest): 1. Command-line: --name Alice --debug --threads 8 2. Environment: APP_NAME=Bob APP_DEBUG=true 3. Config file: name = Charlie 4. Default: threads = 4 Result: name='Alice', debug=True, threads=8 ``` -------------------------------- ### Generate and Write Configuration File Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md This snippet shows how to create an ArgumentParser that can write its current settings to a configuration file. Use the `--write-config` argument to specify the output file. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['app.conf'] ) parser.add_argument('-c', '--config', is_config_file_arg=True) parser.add_argument('-w', '--write-config', is_write_out_config_file_arg=True, help='Write current settings to config file') parser.add_argument('--name', required=True) parser.add_argument('--workers', type=int, default=4) parser.add_argument('--debug', action='store_true') args = parser.parse_args() ``` -------------------------------- ### Writing Configuration to a File Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Shows how to use the 'is_write_out_config_file_arg=True' feature to write the current parsed arguments to a configuration file and then exit. This is useful for generating default configuration files. ```python parser = configargparse.ArgumentParser() parser.add_argument('--name', default='MyApp') parser.add_argument('-w', '--write-config', is_write_out_config_file_arg=True) args = parser.parse_args() # Usage: python app.py --name ProductionApp -w config.ini # Writes current settings to config.ini and exits ``` -------------------------------- ### Basic ArgumentParser Creation Source: https://github.com/bw2/configargparse/blob/master/_autodocs/README.md Create a parser with support for default configuration files, a specific config file parser class, and an environment variable prefix. ```python import configargparse # Create parser with config file and environment variable support parser = configargparse.ArgumentParser( default_config_files=['~/.config/app.yaml'], config_file_parser_class=configargparse.YAMLConfigFileParser, auto_env_var_prefix='APP_' ) ``` -------------------------------- ### Catch ConfigFileParserException Source: https://github.com/bw2/configargparse/blob/master/_autodocs/errors.md Demonstrates how to catch the ConfigFileParserException when parsing arguments that may involve reading from configuration files. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=['app.conf'] ) parser.add_argument('--name') try: args = parser.parse_args() except configargparse.ConfigFileParserException as e: print(f"Error reading config file: {e}") sys.exit(1) ``` -------------------------------- ### Parsing Command-Line Arguments Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Demonstrates basic parsing of command-line arguments after defining required and default arguments. ```python import configargparse parser = configargparse.ArgumentParser() parser.add_argument('--name', required=True) parser.add_argument('--count', type=int, default=1) # Parse command line args = parser.parse_args() ``` -------------------------------- ### Create ArgumentParser with Config Files Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Instantiate an ArgumentParser that uses specified default configuration files and a custom parser class for YAML format. ```python import configargparse # With config files parser = configargparse.ArgumentParser( default_config_files=['~/.config/app.conf'], config_file_parser_class=configargparse.YAMLConfigFileParser ) ``` -------------------------------- ### Config File Search Path Configuration Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Sets up an ArgumentParser to search for configuration files in a specific order, including system-wide, glob patterns, user home, and local directories. Later files override earlier ones. ```python import configargparse parser = configargparse.ArgumentParser( default_config_files=[ '/etc/myapp/app.conf', # System-wide config '/etc/myapp/app.conf.d/*.conf', # Config directory (glob) '~/.myapp_config', # User home config './local.conf' # Local override ] ) # If multiple files exist, values cascade: local.conf > ~/.myapp_config > /etc/... > /etc/.../app.conf.d/*.conf ``` -------------------------------- ### Equivalent ArgumentParser Configurations Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/help-formatters.md Shows two equivalent ways to configure an ArgumentParser using ArgumentDefaultsRawHelpFormatter and its alias DefaultsRawFormatter. ```python import configargparse # These are all equivalent parser1 = configargparse.ArgumentParser( formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter ) parser2 = configargparse.ArgumentParser( formatter_class=configargparse.DefaultsRawFormatter ) # Both provide the same formatting ``` -------------------------------- ### Create ArgumentParser with Environment Variables Source: https://github.com/bw2/configargparse/blob/master/_autodocs/INDEX.md Instantiate an ArgumentParser that automatically prefixes environment variables for configuration. ```python import configargparse # With environment variables parser = configargparse.ArgumentParser(auto_env_var_prefix='APP_') ``` -------------------------------- ### Initialize IniConfigParser (split_ml_text_to_list=True) Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/config-file-parsers.md Configure IniConfigParser to convert multiline strings in INI files into lists. Each line of the multiline string becomes an element in the list. ```python parser = configargparse.ArgumentParser( config_file_parser_class=configargparse.IniConfigParser( ['my_tool'], split_ml_text_to_list=True ) ) parser.add_argument('--urls', action='append') # config.ini: # [my_tool] # urls = # https://example.com/a # https://example.com/b args = parser.parse_args() ``` -------------------------------- ### Initialize Global ArgumentParser Singleton Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/global-functions.md Explicitly creates a global ArgumentParser singleton with specific configuration. Use this when you need to set up the parser with options before other modules access it. ```python import configargparse # Create parser with specific configuration before other modules use it configargparse.init_argument_parser( 'app', default_config_files=['/etc/app.conf', '~/.app_config'], formatter_class=configargparse.ArgumentDefaultsRawHelpFormatter ) # Later, other modules retrieve this pre-configured parser p = configargparse.get_argument_parser('app') p.add_argument('--option') ``` -------------------------------- ### Initialize ArgParser with IniConfigParser Source: https://github.com/bw2/configargparse/blob/master/README.md Set up an ArgParser to use IniConfigParser, specifying default configuration files and binding the parser to specific INI sections. ```python import configargparse parser = configargparse.ArgParser( default_config_files=['setup.cfg', 'my_super_tool.ini'], config_file_parser_class=configargparse.IniConfigParser(['tool:my_super_tool', 'my_super_tool']), ) ... ``` -------------------------------- ### OrderedDict for Configuration Items Source: https://github.com/bw2/configargparse/blob/master/_autodocs/types.md Demonstrates the use of OrderedDict to store configuration items, maintaining the order of entries. Keys are strings, and values can be strings or lists. ```python from collections import OrderedDict # Returned by format_values() and other methods # Keys are strings, values are typically strings or lists config_items = OrderedDict() config_items['name'] = 'MyApp' config_items['debug'] = 'true' config_items['servers'] = ['server1', 'server2'] ``` -------------------------------- ### Add Arguments and Parse Source: https://github.com/bw2/configargparse/blob/master/_autodocs/README.md Defines required, boolean, and integer arguments, then parses them from command-line, config file, environment, and defaults. Finally, it prints the values of the parsed arguments. ```python import configargparse parser = configargparse.ArgumentParser() parser.add_argument('--name', required=True) parser.add_argument('--debug', action='store_true') parser.add_argument('--workers', type=int, default=4) args = parser.parse_args() parser.print_values() ``` -------------------------------- ### Direct Import of ArgumentParser and YAMLConfigFileParser Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Demonstrates how to directly import specific classes from the configargparse library for use in your project. ```python from configargparse import ArgumentParser, YAMLConfigFileParser ``` -------------------------------- ### Handling Lists and Repeated Arguments Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md Shows how to use the `action='append'` to collect multiple values for an argument, either from the command line or a configuration file. This is useful for lists of servers, tags, or other repeatable items. ```python import configargparse parser = configargparse.ArgumentParser() # Append multiple values parser.add_argument('--servers', action='append', help='Server addresses') parser.add_argument('--tags', action='append', help='Tags') args = parser.parse_args() ``` -------------------------------- ### Initialize ConfigparserConfigFileParser Source: https://github.com/bw2/configargparse/blob/master/README.md Instantiate ConfigparserConfigFileParser with custom delimiters, comment prefixes, and other options to control parsing behavior. ```python config = configparser.ArgParser( delimiters=("=",":"), allow_no_value=False, comment_prefixes=("#",";"), inline_comment_prefixes=("#",";"), strict=True, empty_lines_in_values=False, ) ``` -------------------------------- ### Define and Retrieve Singleton Argument Parsers Source: https://github.com/bw2/configargparse/blob/master/README.md Demonstrates how to use configargparse's singleton pattern to manage ArgumentParser instances across different modules in an application. Use get_argument_parser() to retrieve or create a named parser. ```python import configargparse import utils p = configargparse.get_argument_parser() p.add_argument("-x", help="Main module setting") p.add_argument("--m-setting", help="Main module setting") options = p.parse_known_args() # using p.parse_args() here may raise errors. ``` ```python import configargparse p = configargparse.get_argument_parser() p.add_argument("--utils-setting", help="Config-file-settable option for utils") if __name__ == "__main__": options = p.parse_known_args() ``` -------------------------------- ### Format Help Message Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Generates a formatted help message that includes standard argparse help along with configargparse extensions for configuration files and environment variables. Use this to display usage information to the user. ```python parser = configargparse.ArgumentParser( default_config_files=['app.conf'], auto_env_var_prefix='APP_' ) parser.add_argument('--verbose', action='store_true') parser.add_argument('--output') print(parser.format_help()) ``` -------------------------------- ### ArgumentParser with RawTextHelpFormatter Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/help-formatters.md Initializes an ArgumentParser using RawTextHelpFormatter to preserve formatting in all help text and descriptions. ```python parser = configargparse.ArgumentParser( formatter_class=configargparse.RawTextHelpFormatter ) ``` -------------------------------- ### Using configargparse as an argparse Replacement Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Demonstrates how to alias configargparse as 'argparse' for a true drop-in replacement, allowing existing argparse code to be used with configargparse features. ```python import configargparse as argparse # True drop-in replacement! parser = argparse.ArgumentParser() ``` -------------------------------- ### Initialize ArgParser with Composite Config Parser Source: https://github.com/bw2/configargparse/blob/master/README.md Configure an ArgParser to handle both TOML and INI configuration files using a CompositeConfigParser. This allows integration with formats like pyproject.toml and setup.cfg. ```python import configargparse my_tool_sections = ['tool.my_super_tool', 'tool:my_super_tool', 'my_super_tool'] # pyproject.toml like section, setup.cfg like section, custom section parser = configargparse.ArgParser( default_config_files=['setup.cfg', 'my_super_tool.ini'], config_file_parser_class=configargargparse.CompositeConfigParser( [configargparse.TomlConfigParser(my_tool_sections), configargparse.IniConfigParser(my_tool_sections, split_ml_text_to_list=True)] ), ) ... ``` -------------------------------- ### ArgumentParser with Config File Path Arguments Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Initializes an ArgumentParser specifying command-line arguments for setting the config file path and for writing out the config file. ```python import configargparse # With config file specification parser = configargparse.ArgumentParser( args_for_setting_config_path=['-c', '--config'], args_for_writing_out_config_file=['-w', '--write-config'] ) ``` -------------------------------- ### FileType Source: https://github.com/bw2/configargparse/blob/master/_autodocs/types.md A factory for file arguments that automatically opens files. ```APIDOC ## FileType ### Description A factory for file arguments that automatically opens files. ### Usage ```python import configargparse parser = configargparse.ArgumentParser() parser.add_argument('--input', type=configargparse.FileType('r')) parser.add_argument('--output', type=configargparse.FileType('w')) args = parser.parse_args(['--input', 'input.txt', '--output', 'output.txt']) # args.input is an open file object (read mode) # args.output is an open file object (write mode) ``` ``` -------------------------------- ### Custom Config File Opener Function Source: https://github.com/bw2/configargparse/blob/master/_autodocs/configuration.md Provides a custom function to handle opening configuration files, allowing retrieval from remote sources like HTTP. This function is passed to the ArgumentParser. ```python import configargparse import io def get_config_from_server(path, mode='r'): """Load config from remote server instead of disk""" if path.startswith('http://'): import urllib.request response = urllib.request.urlopen(path) content = response.read().decode('utf-8') return io.StringIO(content) else: return open(path, mode) parser = configargparse.ArgumentParser( default_config_files=['http://config-server/app.conf'], config_file_open_func=get_config_from_server ) parser.add_argument('--name') args = parser.parse_args() ``` -------------------------------- ### get_possible_config_keys(action) Source: https://github.com/bw2/configargparse/blob/master/_autodocs/api-reference/argument-parser.md Retrieves a list of configuration file keys that can be used to set the value for a given action. ```APIDOC ## get_possible_config_keys(action) ### Description Returns list of config file keys that can set the given action's value. ### Parameters #### Path Parameters - **action** (argparse.Action) - Required - The action to get config keys for. ### Returns `list[str]` - Config keys for this action. ### Example ```python parser = configargparse.ArgumentParser() action = parser.add_argument('--my-option') keys = parser.get_possible_config_keys(action) # keys = ['my-option', '--my-option'] ``` ``` -------------------------------- ### Module Import of configargparse Source: https://github.com/bw2/configargparse/blob/master/_autodocs/module-overview.md Shows the standard way to import the entire configargparse module and access its components using the module name. ```python import configargparse parser = configargparse.ArgumentParser() ``` -------------------------------- ### Testing with Explicit Configuration and Overrides Source: https://github.com/bw2/configargparse/blob/master/_autodocs/examples.md Create test arguments by providing configuration file contents and environment variable overrides. This is useful for unit testing argument parsing logic. ```python import configargparse def create_test_args(**overrides): config = """ name = TestApp debug = true workers = 2 """ parser = configargparse.ArgumentParser() parser.add_argument('--name', required=True) parser.add_argument('--debug', action='store_true') parser.add_argument('--workers', type=int, default=4) args = parser.parse_args( config_file_contents=config, env_vars=overrides or {} ) return args # Test 1: Default config args = create_test_args() assert args.name == 'TestApp' assert args.debug == True # Test 2: Override with environment variable args = create_test_args(DEBUG='false') assert args.debug == False ```