././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7558975
configargparse-1.9.0/ 0000755 0001751 0001751 00000000000 15270233512 014161 5 ustar 00runner runner ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9285102
configargparse-1.9.0/.coveragerc 0000644 0001751 0001751 00000000213 15270233507 016302 0 ustar 00runner runner [run]
source = .
relative_files = true
omit =
setup.py
[report]
skip_covered = false
show_missing = true
[html]
show_contexts = true
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9285102
configargparse-1.9.0/.editorconfig 0000644 0001751 0001751 00000000346 15270233507 016645 0 ustar 00runner runner # https://editorconfig.org/
root = true
[*]
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
charset = utf-8
[*.py]
max_line_length = 88
[*.yml]
indent_size = 2
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9285102
configargparse-1.9.0/.git-blame-ignore-revs 0000644 0001751 0001751 00000000405 15270233507 020264 0 ustar 00runner runner # .git-blame-ignore-revs used to ignore SHAs from git blame
# applied automatically in Github, use the command
# `git config blame.ignoreRevsFile .git-blame-ignore-revs` to config git to
# use it as well
# black format
0962f7378ceec1218e30489352df4c80533d4cb8
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7546265
configargparse-1.9.0/.github/ 0000755 0001751 0001751 00000000000 15270233512 015521 5 ustar 00runner runner ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7547011
configargparse-1.9.0/.github/workflows/ 0000755 0001751 0001751 00000000000 15270233512 017556 5 ustar 00runner runner ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298508
configargparse-1.9.0/.github/workflows/apidocs.yml 0000644 0001751 0001751 00000001637 15270233507 021736 0 ustar 00runner runner name: apidocs
on:
push:
branches: [ master ]
tags:
- '*'
# Set minimal permissions by default
permissions: {}
jobs:
deploy:
runs-on: macos-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Set up Python 3.8
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Install requirements for documentation generation
run: python -m pip install --upgrade pip pydoctor
- name: Generate API documentation with pydoctor
run: ./apidocs.sh
- name: Push API documentation to Github Pages
uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e # v4.0.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./apidocs
commit_message: "Generate API documentation"
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/.github/workflows/test.yml 0000644 0001751 0001751 00000012773 15270233507 021276 0 ustar 00runner runner name: unit tests
on:
push:
branches: [ master ]
tags:
- '*'
pull_request:
# Set minimal permissions by default
permissions: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: 3.13
- name: Install linters
run: python -m pip install --upgrade pip black zizmor pydoctor
- name: Black
run: black . --check
- name: Zizmor
run: find .github/workflows -name '*.yml' | xargs zizmor --config .github/zizmor.yml
- name: Pydoctor
run: pydoctor ./configargparse.py --intersphinx=https://docs.python.org/3/objects.inv --docformat=google -W
test:
name: ${{ matrix.os }} py${{ matrix.python-version }} ${{ matrix.use-docker && '(docker)' || '' }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- name: Legacy Python on Ubuntu
os: ubuntu-latest
python-version: '3.6'
use-docker: true
- name: Legacy Python on Ubuntu
os: ubuntu-latest
python-version: '3.7'
use-docker: true
- name: Legacy Python on Ubuntu
os: ubuntu-latest
python-version: '3.8'
use-docker: true
# setup-python has no Python 3.9 for the Ubuntu version that
# ubuntu-latest now points to, so run it in Docker instead
- name: Legacy Python on Ubuntu
os: ubuntu-latest
python-version: '3.9'
use-docker: true
exclude:
- os: ubuntu-latest
python-version: '3.9'
use-docker: false
os: [ubuntu-latest, windows-latest, macos-latest]
python-version: ['3.9','3.10','3.11','3.12','3.13','3.14']
use-docker: [false]
fail-fast: false
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Set up Python ${{ matrix.python-version }}
if: ${{ !matrix.use-docker }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Run tests with Docker
if: ${{ matrix.use-docker }}
run: |
docker run --rm -v ${{ github.workspace }}:/app -w /app python:${{ matrix.python-version }} bash -c "
python -m pip install --upgrade pip setuptools wheel tox
python -m pip install '.[test]'
pytest --cov-branch --cov-context=test --cov=.
"
- name: Run tests
if: ${{ !matrix.use-docker }}
run: |
python -m pip install --upgrade pip setuptools wheel tox
python -m pip install '.[test]'
pytest --cov-branch --cov-context=test --cov=.
- name: Set artifact name
shell: bash
run: |
ARTIFACT_NAME="coverage-${{ runner.os }}-py-${{ matrix.python-version }}"
ARTIFACT_NAME="${ARTIFACT_NAME//./}"
echo "ARTIFACT_NAME=$ARTIFACT_NAME" >> "$GITHUB_ENV"
- name: Upload coverage artifact
uses: actions/upload-artifact@v4
with:
include-hidden-files: true
if-no-files-found: error
name: ${{ env.ARTIFACT_NAME }}
path: .coverage
retention-days: 1
coverage:
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: 3.13
- name: Download artifacts
uses: actions/download-artifact@v4
with:
path: downloaded_artifacts
- name: Clean up temporary artifacts
uses: geekyeggo/delete-artifact@f275313e70c08f6120db482d7a6b98377786765b # v5.1.0
with:
name: coverage-*
- name: Install dependencies
run: pip install coverage
- name: Combine coverage.py
run: |
coverage combine $(find downloaded_artifacts/ -type f | xargs)
coverage xml
coverage html
coverage report --format=markdown >> $GITHUB_STEP_SUMMARY
cp coverage.xml htmlcov/coverage.xml
cp .coverage htmlcov/.coverage
- name: Upload single coverage artifact
uses: actions/upload-artifact@v4
with:
include-hidden-files: true
if-no-files-found: error
name: htmlcov
path: htmlcov
# Retention days for main branch is 90 days, for other branches is 1 day
retention-days: ${{ github.ref == 'refs/heads/master' && 90 || 1 }}
release:
needs: [test, coverage]
name: PyPI
runs-on: ubuntu-latest
environment: pypi
permissions:
id-token: write
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Set up Python 3.12
uses: actions/setup-python@v5
with:
python-version: 3.12
- name: Install build dependencies
run: |
python -m pip install -U setuptools wheel setuptools-scm
- name: Build
run: |
python setup.py --quiet build check sdist bdist_wheel
ls -alh ./dist/
- name: Publish to PyPI - on tag
if: startsWith(github.ref, 'refs/tags/')
uses: pypa/gh-action-pypi-publish@release/v1
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/.github/zizmor.yml 0000644 0001751 0001751 00000000213 15270233507 017576 0 ustar 00runner runner rules:
unpinned-uses:
ignore: []
config:
policies:
actions/*: ref-pin
pypa/gh-action-pypi-publish: ref-pin
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/.gitignore 0000644 0001751 0001751 00000000704 15270233507 016156 0 ustar 00runner runner apidocs
*.py[cod]
# C extensions
*.so
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
lib
lib64
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
htmlcov
#tox.ini
#nosetests.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Complexity
output/*.html
output/*/index.html
# Sphinx
docs/_build
# IDEs
.idea
.claude
.memory
.code_review*
.eggs/
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/CONTRIBUTING.rst 0000644 0001751 0001751 00000005107 15270233507 016631 0 ustar 00runner runner Contributing to ConfigArgParse
------------------------------
What you can do
~~~~~~~~~~~~~~~
If you like the project and think you could help with making it better, there are many ways you can do it:
- Create an issue to report a bug or suggest a new feature
- Triage old issues that need a refresh
- Implement fixes for existing issues
- Help with improving the documentation
- Spread the word about the project to your colleagues, friends, blogs or any other channels
- Any other things you could imagine
Any contribution would be of great help and we'll highly appreciate it!
If you have any questions, please create a new issue.
Development process
~~~~~~~~~~~~~~~~~~~
Create a fork of the git repository and checkout a new branch from master branch.
The branch name may start with an associated issue number so that we can easily cross-reference them.
For example, use ``1234-some-brach-name`` as the name of the branch working to fix issue 1234.
Once your changes are ready and are passing the automated tests, open a pull request.
Don’t forget to sync your fork once in a while to work from the latest revision.
Pre-commit checks
~~~~~~~~~~~~~~~~~
- Run unit tests: ``pytest``.
Review process
~~~~~~~~~~~~~~
- Code changes and code added should have tests: untested code is buggy code and should
not be accepted by reviewers.
- All code changes must be reviewed by at least one maintainer who is not an author
of the code being added.
- When a reviewer completes a review, they should always say what the next step(s) should be:
- Ok we can merge the patch as is
- Some optional changes requested
- Some required changes are requested
- An issue should be opened to tackle another problem discovered during the coding process.
- If a substantial change is pushed after a review, a follow-up review should be done.
Small changes and nit-picks do not required follow-up reviews.
Release process
~~~~~~~~~~~~~~~
The following is a high level overview and might not match the current state of things.
- Edit setup.py to update the version number and create a PR with this change (suggested branch name format: ``release-1.5.1``)
- Once that PR is approved and merged, the *owner* should push a new tag with the same name as the version i.e. ``1.5.1`` by running `git pull; git tag 1.5.1; git push --tags`.
This will trigger the PyPi release process. Monitor the process in the GitHub action UI...
---
owner: people with administrative rights on the repo, only they are able to push a new tag.
maintainers: people with push rights, they can merge PR if the requirements are met.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7549577
configargparse-1.9.0/ConfigArgParse.egg-info/ 0000755 0001751 0001751 00000000000 15270233512 020505 5 ustar 00runner runner ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7465415
configargparse-1.9.0/ConfigArgParse.egg-info/PKG-INFO 0000644 0001751 0001751 00000060461 15270233512 021611 0 ustar 00runner runner Metadata-Version: 2.4
Name: ConfigArgParse
Version: 1.9.0
Summary: A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.
Home-page: https://github.com/bw2/ConfigArgParse
License: MIT
Keywords: options,argparse,ConfigArgParse,config,environment variables,envvars,ENV,environment,optparse,YAML,INI
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: toml
Requires-Dist: toml; extra == "toml"
Provides-Extra: yaml
Requires-Dist: PyYAML; extra == "yaml"
Provides-Extra: test
Requires-Dist: black; extra == "test"
Requires-Dist: mock; extra == "test"
Requires-Dist: toml; extra == "test"
Requires-Dist: PyYAML; extra == "test"
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: pytest-subtests; extra == "test"
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-python
Dynamic: summary
# ConfigArgParse
[](https://pypi.python.org/pypi/ConfigArgParse)
[](https://pypi.python.org/pypi/ConfigArgParse)
[](https://pepy.tech/project/configargparse)
[](https://github.com/bw2/ConfigArgParse/actions/workflows/test.yml)
[](https://bw2.github.io/ConfigArgParse/)
## Overview
Applications with more than a handful of user-settable options are best
configured through a combination of command line args, config files,
hard-coded defaults, and in some cases, environment variables.
Python's command line parsing modules such as argparse have very limited
support for config files and environment variables, so this module
extends argparse to add these features.
**API docs:** https://bw2.github.io/ConfigArgParse/
**PyPI:** http://pypi.python.org/pypi/ConfigArgParse
## Install
To install this library, run:
```
pip install ConfigArgParse
```
## Features
- command-line, config file, env var, and default settings can now be
defined, documented, and parsed in one go using a single API (if a
value is specified in more than one way then: command line >
environment variables > config file values > defaults)
- config files can have .ini or .yaml style syntax (eg. key=value or
key: value)
- user can provide a config file via a normal-looking command line arg
(eg. -c path/to/config.txt) rather than the argparse-style @config.txt
- one or more default config file paths can be specified
(eg. `['/etc/bla.conf', '~/.my_config']`)
- all argparse functionality is fully supported, so this module can
serve as a drop-in replacement (verified by argparse unittests).
- env vars and config file keys & syntax are automatically documented
in the -h help message
- new method `print_values()` can report keys & values and where
they were set (eg. command line, env var, config file, or default).
- lite-weight (no 3rd-party library dependencies except (optionally) PyYAML)
- extensible (`ConfigFileParser` can be subclassed to define a new
config file format)
- unittested by running the unittests that came with argparse but on
configargparse
## Example
*config_test.py*:
Script that defines 4 options and a positional arg and then parses and prints the values. Also,
it prints out the help message as well as the string produced by `format_values()` to show
what they look like.
```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
```
*config.txt:*
Since the script above set the config file as required=True, lets create a config file to give it:
```python
# settings for config_test.py
genome = HCMV # cytomegalovirus genome
dbsnp = /data/dbsnp/variants.vcf
```
*command line:*
Now run the script and pass it the config file:
```bash
DBSNP_PATH=/data/dbsnp/variants_v2.vcf python config_test.py --my-config config.txt f1.vcf f2.vcf
```
*output:*
Here is the result:
```bash
Namespace(dbsnp='/data/dbsnp/variants_v2.vcf', genome='HCMV', my_config='config.txt', v=False, vcf=['f1.vcf', 'f2.vcf'])
----------
usage: config_test.py [-h] -c MY_CONFIG --genome GENOME [-v] [-d DBSNP]
vcf [vcf ...]
Args that start with '--' (eg. --genome) can also be set in a config file
(/etc/app/conf.d/*.conf or ~/.my_settings or specified via -c). Config file
syntax allows: key=value, flag=true, stuff=[a,b,c] (for details, see syntax at
https://goo.gl/R74nmi). If an arg is specified in more than one place, then
commandline values override environment variables which override config file
values which override defaults.
positional arguments:
vcf variant file(s)
optional arguments:
-h, --help show this help message and exit
-c MY_CONFIG, --my-config MY_CONFIG
config file path
--genome GENOME path to genome file
-v verbose
-d DBSNP, --dbsnp DBSNP
known variants .vcf [env var: DBSNP_PATH]
----------
Command Line Args: --my-config config.txt f1.vcf f2.vcf
Environment Variables:
DBSNP_PATH: /data/dbsnp/variants_v2.vcf
Config File (config.txt):
genome: HCMV
```
## Special Values
Under the hood, configargparse handles environment variables and config file
values by converting them to their corresponding command line arg. For
example, "key = value" will be processed as if "--key value" was specified
on the command line.
Also, the following special values (whether in a config file or an environment
variable) are handled in a special way to support booleans and lists:
- `key = true` is handled as if "--key" was specified on the command line.
In your python code this key must be defined as a boolean flag
(eg. action="store_true" or similar).
- `key = false` is handled as if "--key" was not specified (or, for an arg
defined with action=argparse.BooleanOptionalAction, as if "--no-key" was
specified). It still counts as setting the key, though, so a `key = true`
from a lower-priority source (eg. a config file, when `key = false` comes
from an environment variable) is ignored.
- `key = [value1, value2, ...]` is handled as if "--key value1 --key value2"
etc. was specified on the command line. In your python code this key must
be defined as a list (eg. action="append").
## Config File Syntax
Only command line args that have a long version (eg. one that starts with '--')
can be set in a config file. For example, "--color" can be set by putting
"color=green" in a config file. The config file syntax depends on the constructor
arg: `config_file_parser_class` which can be set to one of the provided
classes:
- `DefaultConfigFileParser`
- `YAMLConfigFileParser`
- `ConfigparserConfigFileParser`
- `IniConfigParser`
- `TomlConfigParser`
- `CompositeConfigParser`
or to your own subclass of the `ConfigFileParser` abstract class.
#### *DefaultConfigFileParser* - the full range of valid syntax is:
```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]
```
#### *YAMLConfigFileParser* - allows a subset of YAML syntax (http://goo.gl/VgT2DU)
```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
```
#### *ConfigparserConfigFileParser* - allows a subset of python's configparser
module syntax (https://docs.python.org/3.7/library/configparser.html). In
particular the following configparser options are set:
```python
config = configparser.ArgParser(
delimiters=("=",":"),
allow_no_value=False,
comment_prefixes=("#",";"),
inline_comment_prefixes=("#",";"),
strict=True,
empty_lines_in_values=True,
)
```
Because of `empty_lines_in_values=True`, a line indented more than the key above
it continues that key's value, even after a blank line or a comment line, rather
than starting a new key.
Once configparser parses the config file all section names are removed, thus all
keys must have unique names regardless of which INI section they are defined
under. configparser also lowercases all keys, so an option whose name contains
uppercase letters (e.g. `--outputDir`) can't be set from this kind of config
file. A config file that `write_config_file` saved for such an option holds the
lowercased key (`outputdir`), so loading it fails with "unrecognized arguments"
unless `ignore_unknown_config_file_keys=True`, which skips that setting instead.
Also, any keys which have python list syntax are converted to lists by
evaluating them as python code using ast.literal_eval
(https://docs.python.org/3/library/ast.html#ast.literal_eval). To facilitate
this all multi-line values are converted to single-line values. Thus multi-line
string values will have all new-lines converted to spaces. Note, since key-value
pairs that have python dictionary syntax are saved as single-line strings, even
if formatted across multiple lines in the config file, dictionaries can be read
in and converted to valid python dictionaries with PyYAML's safe_load. Example
given below:
```python
# inside your config file (e.g. config.ini)
[section1] # INI sections treated as comments
system1_settings: { # start of multi-line dictionary
'a':True,
'b':[2, 4, 8, 16],
'c':{'start':0, 'stop':1000},
'd':'experiment 32 testing simulation with parameter a on'
} # end of multi-line dictionary value
.......
# in your configargparse setup
import configargparse
import yaml
parser = configargparse.ArgParser(
config_file_parser_class=configargparse.ConfigparserConfigFileParser
)
parser.add_argument('--system1_settings', type=yaml.safe_load)
args = parser.parse_args() # now args.system1 is a valid python dict
```
#### *IniConfigParser* - INI parser with support for sections.
This parser somewhat resembles `ConfigparserConfigFileParser`. It uses configparser and applies the same kind of processing to
values written with python list syntax.
With the following additions:
- Must be created with argument to bind the parser to a list of sections.
- Does not convert multiline strings to single line.
- Optional support for converting multiline strings to list (if `split_ml_text_to_list=True`).
- Optional support for quoting strings in config file
(useful when text must not be converted to list or when text
should contain trailing whitespaces).
This config parser can be used to integrate with `setup.cfg` files.
Example:
```
# 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.
```
If you use `IniConfigParser(sections, split_ml_text_to_list=True)`:
```
# the same rules are applicable with the following changes:
[my-software]
# how to specify a list arg (eg. arg which has action="append")
repeatable-option = # Just enter one value per line (the list literal format can also be used)
https://docs.python.org/3/objects.inv
https://twistedmatrix.com/documents/current/api/objects.inv
# how to specify a multiline text (you have to quote it):
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.
'''
```
Usage:
```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']),
)
...
```
#### *TomlConfigParser* - TOML parser with support for sections.
[TOML](https://github.com/toml-lang/toml/blob/main/toml.md) parser. This config parser can be used to integrate with `pyproject.toml` files.
Requires installation of [toml](https://pypi.org/project/toml/) for Python versions
below 3.11, and for writing a config file out on any version, since the standard
library's `tomllib` can only read.
Example:
```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
# 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.
'''
```
Usage:
```python
import configargparse
parser = configargparse.ArgParser(
default_config_files=['pyproject.toml', 'my_super_tool.toml'],
config_file_parser_class=configargparse.TomlConfigParser(['tool.my_super_tool']),
)
...
```
#### *CompositeConfigParser* - parses more than one config file format.
This parser will successively try to parse the file with each parser, until it succeeds,
else fail showing all encountered error messages.
The following code will make configargparse understand both TOML and INI formats.
Making it easy to integrate in both `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=configargparse.CompositeConfigParser(
[configargparse.TomlConfigParser(my_tool_sections),
configargparse.IniConfigParser(my_tool_sections, split_ml_text_to_list=True)]
),
)
...
```
Note that it's required to put the TOML parser first because the INI syntax basically would accept anything whereas TOML is a bit more strict.
## ArgParser Singletons
To make it easier to configure different modules in an application,
configargparse provides globally-available ArgumentParser instances
via configargparse.get_argument_parser('name') (similar to
logging.getLogger('name')).
Here is an example of an application with a utils module that also
defines and retrieves its own command-line args.
*main.py*
```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.
```
*utils.py*
```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()
```
## Help Formatters
`ArgumentDefaultsRawHelpFormatter` is a new HelpFormatter that both adds
default values AND disables line-wrapping. It can be passed to the constructor:
`ArgParser(.., formatter_class=ArgumentDefaultsRawHelpFormatter)`
## Aliases
The configargparse.ArgumentParser API inherits its class and method
names from argparse and also provides the following shorter alias names for
convenience:
**Class Aliases:**
- `ArgParser` = `ArgumentParser` (create a new instance)
- `Parser` = `ArgumentParser`
**Method Aliases:**
- `p.add(..)` = `p.add_argument(..)`
- `p.add_arg(..)` = `p.add_argument(..)`
- `p.parse(..)` = `p.parse_args(..)`
- `p.parse_known(..)` = `p.parse_known_args(..)`
**Function Aliases (for global singleton):**
- `configargparse.get_arg_parser()` = `configargparse.get_argument_parser()`
- `configargparse.get_parser()` = `configargparse.get_argument_parser()`
- `configargparse.getArgumentParser()` = `configargparse.get_argument_parser()`
- `configargparse.getArgParser()` = `configargparse.get_argument_parser()`
- `configargparse.getParser()` = `configargparse.get_argument_parser()`
- `configargparse.initArgumentParser()` = `configargparse.init_argument_parser()`
**HelpFormatter Aliases:**
- `RawFormatter` = `RawDescriptionHelpFormatter`
- `DefaultsFormatter` = `ArgumentDefaultsHelpFormatter`
- `DefaultsRawFormatter` = `ArgumentDefaultsRawHelpFormatter`
## API Documentation
You can review the generated API Documentation for the `configargparse` module: [HERE](https://bw2.github.io/ConfigArgParse/)
## Design Notes
Unit tests:
tests/test_configargparse.py contains custom unittests for features
specific to this module (such as config file and env-var support), as
well as a hook to load and run argparse unittests (see the built-in
test.test_argparse module) but on configargparse in place of argparse.
This ensures that configargparse will work as a drop in replacement for
argparse in all usecases.
Previously existing modules (PyPI search keywords: config argparse):
- argparse (built-in module Python v2.7+)
- Good:
- fully featured command line parsing
- can read args from files using an easy to understand mechanism
- Bad:
- syntax for specifying config file path is unusual (eg. @file.txt) and not described in the user help message.
- default config file syntax doesn't support comments and is unintuitive (eg. --namevalue)
- no support for environment variables
- ConfArgParse v1.0.15 (https://pypi.python.org/pypi/ConfArgParse)
- Good:
- extends argparse with support for config files parsed by ConfigParser
- clear documentation in README
- Bad:
- config file values are processed using ArgumentParser.set_defaults(..) which means "required" and "choices" are not handled as expected. For example, if you specify a required value in a config file, you still have to specify it again on the command line.
- doesn't work with Python 3 yet
- no unit tests, code not well documented
- appsettings v0.5 (https://pypi.python.org/pypi/appsettings)
- Good:
- supports config file (yaml format) and env_var parsing
- supports config-file-only setting for specifying lists and dicts
- Bad:
- passes in config file and env settings via parse_args namespace param
- tests not finished and don't work with Python 3 (import StringIO)
- argparse_config v0.5.1 (https://pypi.python.org/pypi/argparse_config)
- Good:
- similar features to ConfArgParse v1.0.15
- Bad:
- doesn't work with Python 3 (error during pip install)
- yconf v0.3.2 - (https://pypi.python.org/pypi/yconf) - features and interface not that great
- hieropt v0.3 - (https://pypi.python.org/pypi/hieropt) - doesn't appear to be maintained, couldn't find documentation
- configurati v0.2.3 - (https://pypi.python.org/pypi/configurati)
- Good:
- JSON, YAML, or Python configuration files
- handles rich data structures such as dictionaries
- can group configuration names into sections (like .ini files)
- Bad:
- doesn't work with Python 3
- 2+ years since last release to PyPI
- apparently unmaintained
Design choices:
1. all options must be settable via command line. Having options that
can only be set using config files or env. vars adds complexity to
the API, and is not a useful enough feature since the developer can
split up options into sections and call a section "config file keys",
with command line args that are just "--" plus the config key.
2. config file and env. var settings should be processed by appending
them to the command line (another benefit of #1). This is an
easy-to-implement solution and implicitly takes care of checking that
all "required" args are provided, etc., plus the behavior should be
easy for users to understand.
3. configargparse shouldn't override argparse's
convert_arg_line_to_args method so that all argparse unit tests
can be run on configargparse.
4. in terms of what to allow for config file keys, the "dest" value of
an option can't serve as a valid config key because many options can
have the same dest. Instead, since multiple options can't use the
same long arg (eg. "--long-arg-x"), let the config key be either
"--long-arg-x" or "long-arg-x". This means the developer can allow
only a subset of the command-line args to be specified via config
file (eg. short args like -x would be excluded). Also, that way
config keys are automatically documented whenever the command line
args are documented in the help message.
5. don't force users to put config file settings in the right .ini [sections].
This doesn't have a clear benefit since all options are command-line settable,
and so have a globally unique key anyway.
Enforcing sections just makes things harder for the user and adds complexity to the implementation.
NOTE: This design choice was preventing configargparse from integrating with common Python project
config files like setup.cfg or pyproject.toml,
so additional parser classes were added that parse only a subset of the values defined in INI or
TOML config files.
6. if necessary, config-file-only args can be added later by
implementing a separate add method and using the namespace arg as in
appsettings_v0.5
Relevant sites:
- http://stackoverflow.com/questions/6133517/parse-config-file-environment-and-command-line-arguments-to-get-a-single-coll
- http://tricksntweaks.blogspot.com/2013_05_01_archive.html
- http://www.youtube.com/watch?v=vvCwqHgZJc8#t=35
## Versioning
This software follows [Semantic Versioning](http://semver.org/)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7532685
configargparse-1.9.0/ConfigArgParse.egg-info/SOURCES.txt 0000644 0001751 0001751 00000001177 15270233512 022377 0 ustar 00runner runner .coveragerc
.editorconfig
.git-blame-ignore-revs
.gitignore
CONTRIBUTING.rst
LICENSE
MANIFEST.in
README.md
SECURITY.md
apidocs.sh
configargparse.py
setup.py
.github/zizmor.yml
.github/workflows/apidocs.yml
.github/workflows/test.yml
ConfigArgParse.egg-info/PKG-INFO
ConfigArgParse.egg-info/SOURCES.txt
ConfigArgParse.egg-info/dependency_links.txt
ConfigArgParse.egg-info/requires.txt
ConfigArgParse.egg-info/scm_file_list.json
ConfigArgParse.egg-info/scm_version.json
ConfigArgParse.egg-info/top_level.txt
apidocs_templates/extra.css
apidocs_templates/header.html
tests/__init__.py
tests/test_configargparse.py
tests/test_end_of_options.py ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7475085
configargparse-1.9.0/ConfigArgParse.egg-info/dependency_links.txt 0000644 0001751 0001751 00000000001 15270233512 024553 0 ustar 00runner runner
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7478197
configargparse-1.9.0/ConfigArgParse.egg-info/requires.txt 0000644 0001751 0001751 00000000135 15270233512 023104 0 ustar 00runner runner
[test]
black
mock
toml
PyYAML
pytest
pytest-cov
pytest-subtests
[toml]
toml
[yaml]
PyYAML
././@PaxHeader 0000000 0000000 0000000 00000000031 00000000000 010207 x ustar 00 25 mtime=1793144649.7454
configargparse-1.9.0/ConfigArgParse.egg-info/scm_file_list.json 0000644 0001751 0001751 00000001017 15270233512 024213 0 ustar 00runner runner {
"files": [
".coveragerc",
".editorconfig",
".git-blame-ignore-revs",
".github/workflows/apidocs.yml",
".github/workflows/test.yml",
".github/zizmor.yml",
".gitignore",
"CONTRIBUTING.rst",
"LICENSE",
"MANIFEST.in",
"README.md",
"SECURITY.md",
"apidocs.sh",
"apidocs_templates/extra.css",
"apidocs_templates/header.html",
"configargparse.py",
"setup.py",
"tests/__init__.py",
"tests/test_configargparse.py",
"tests/test_end_of_options.py"
]
}
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1793144649.740286
configargparse-1.9.0/ConfigArgParse.egg-info/scm_version.json 0000644 0001751 0001751 00000000240 15270233512 023723 0 ustar 00runner runner {
"tag": "1.9.0",
"distance": 0,
"node": "g1829aa14c317374aa1467e1d01f99472282183ff",
"dirty": false,
"branch": "HEAD",
"node_date": "2026-10-27"
}
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1793144649.747853
configargparse-1.9.0/ConfigArgParse.egg-info/top_level.txt 0000644 0001751 0001751 00000000017 15270233512 023235 0 ustar 00runner runner configargparse
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/LICENSE 0000644 0001751 0001751 00000002056 15270233507 015175 0 ustar 00runner runner The MIT License (MIT)
Copyright (c) 2015 bw2
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/MANIFEST.in 0000644 0001751 0001751 00000000062 15270233507 015721 0 ustar 00runner runner include LICENSE
include README.md
include tests/*
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7558684
configargparse-1.9.0/PKG-INFO 0000644 0001751 0001751 00000060461 15270233512 015265 0 ustar 00runner runner Metadata-Version: 2.4
Name: ConfigArgParse
Version: 1.9.0
Summary: A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.
Home-page: https://github.com/bw2/ConfigArgParse
License: MIT
Keywords: options,argparse,ConfigArgParse,config,environment variables,envvars,ENV,environment,optparse,YAML,INI
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: toml
Requires-Dist: toml; extra == "toml"
Provides-Extra: yaml
Requires-Dist: PyYAML; extra == "yaml"
Provides-Extra: test
Requires-Dist: black; extra == "test"
Requires-Dist: mock; extra == "test"
Requires-Dist: toml; extra == "test"
Requires-Dist: PyYAML; extra == "test"
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: pytest-subtests; extra == "test"
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-python
Dynamic: summary
# ConfigArgParse
[](https://pypi.python.org/pypi/ConfigArgParse)
[](https://pypi.python.org/pypi/ConfigArgParse)
[](https://pepy.tech/project/configargparse)
[](https://github.com/bw2/ConfigArgParse/actions/workflows/test.yml)
[](https://bw2.github.io/ConfigArgParse/)
## Overview
Applications with more than a handful of user-settable options are best
configured through a combination of command line args, config files,
hard-coded defaults, and in some cases, environment variables.
Python's command line parsing modules such as argparse have very limited
support for config files and environment variables, so this module
extends argparse to add these features.
**API docs:** https://bw2.github.io/ConfigArgParse/
**PyPI:** http://pypi.python.org/pypi/ConfigArgParse
## Install
To install this library, run:
```
pip install ConfigArgParse
```
## Features
- command-line, config file, env var, and default settings can now be
defined, documented, and parsed in one go using a single API (if a
value is specified in more than one way then: command line >
environment variables > config file values > defaults)
- config files can have .ini or .yaml style syntax (eg. key=value or
key: value)
- user can provide a config file via a normal-looking command line arg
(eg. -c path/to/config.txt) rather than the argparse-style @config.txt
- one or more default config file paths can be specified
(eg. `['/etc/bla.conf', '~/.my_config']`)
- all argparse functionality is fully supported, so this module can
serve as a drop-in replacement (verified by argparse unittests).
- env vars and config file keys & syntax are automatically documented
in the -h help message
- new method `print_values()` can report keys & values and where
they were set (eg. command line, env var, config file, or default).
- lite-weight (no 3rd-party library dependencies except (optionally) PyYAML)
- extensible (`ConfigFileParser` can be subclassed to define a new
config file format)
- unittested by running the unittests that came with argparse but on
configargparse
## Example
*config_test.py*:
Script that defines 4 options and a positional arg and then parses and prints the values. Also,
it prints out the help message as well as the string produced by `format_values()` to show
what they look like.
```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
```
*config.txt:*
Since the script above set the config file as required=True, lets create a config file to give it:
```python
# settings for config_test.py
genome = HCMV # cytomegalovirus genome
dbsnp = /data/dbsnp/variants.vcf
```
*command line:*
Now run the script and pass it the config file:
```bash
DBSNP_PATH=/data/dbsnp/variants_v2.vcf python config_test.py --my-config config.txt f1.vcf f2.vcf
```
*output:*
Here is the result:
```bash
Namespace(dbsnp='/data/dbsnp/variants_v2.vcf', genome='HCMV', my_config='config.txt', v=False, vcf=['f1.vcf', 'f2.vcf'])
----------
usage: config_test.py [-h] -c MY_CONFIG --genome GENOME [-v] [-d DBSNP]
vcf [vcf ...]
Args that start with '--' (eg. --genome) can also be set in a config file
(/etc/app/conf.d/*.conf or ~/.my_settings or specified via -c). Config file
syntax allows: key=value, flag=true, stuff=[a,b,c] (for details, see syntax at
https://goo.gl/R74nmi). If an arg is specified in more than one place, then
commandline values override environment variables which override config file
values which override defaults.
positional arguments:
vcf variant file(s)
optional arguments:
-h, --help show this help message and exit
-c MY_CONFIG, --my-config MY_CONFIG
config file path
--genome GENOME path to genome file
-v verbose
-d DBSNP, --dbsnp DBSNP
known variants .vcf [env var: DBSNP_PATH]
----------
Command Line Args: --my-config config.txt f1.vcf f2.vcf
Environment Variables:
DBSNP_PATH: /data/dbsnp/variants_v2.vcf
Config File (config.txt):
genome: HCMV
```
## Special Values
Under the hood, configargparse handles environment variables and config file
values by converting them to their corresponding command line arg. For
example, "key = value" will be processed as if "--key value" was specified
on the command line.
Also, the following special values (whether in a config file or an environment
variable) are handled in a special way to support booleans and lists:
- `key = true` is handled as if "--key" was specified on the command line.
In your python code this key must be defined as a boolean flag
(eg. action="store_true" or similar).
- `key = false` is handled as if "--key" was not specified (or, for an arg
defined with action=argparse.BooleanOptionalAction, as if "--no-key" was
specified). It still counts as setting the key, though, so a `key = true`
from a lower-priority source (eg. a config file, when `key = false` comes
from an environment variable) is ignored.
- `key = [value1, value2, ...]` is handled as if "--key value1 --key value2"
etc. was specified on the command line. In your python code this key must
be defined as a list (eg. action="append").
## Config File Syntax
Only command line args that have a long version (eg. one that starts with '--')
can be set in a config file. For example, "--color" can be set by putting
"color=green" in a config file. The config file syntax depends on the constructor
arg: `config_file_parser_class` which can be set to one of the provided
classes:
- `DefaultConfigFileParser`
- `YAMLConfigFileParser`
- `ConfigparserConfigFileParser`
- `IniConfigParser`
- `TomlConfigParser`
- `CompositeConfigParser`
or to your own subclass of the `ConfigFileParser` abstract class.
#### *DefaultConfigFileParser* - the full range of valid syntax is:
```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]
```
#### *YAMLConfigFileParser* - allows a subset of YAML syntax (http://goo.gl/VgT2DU)
```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
```
#### *ConfigparserConfigFileParser* - allows a subset of python's configparser
module syntax (https://docs.python.org/3.7/library/configparser.html). In
particular the following configparser options are set:
```python
config = configparser.ArgParser(
delimiters=("=",":"),
allow_no_value=False,
comment_prefixes=("#",";"),
inline_comment_prefixes=("#",";"),
strict=True,
empty_lines_in_values=True,
)
```
Because of `empty_lines_in_values=True`, a line indented more than the key above
it continues that key's value, even after a blank line or a comment line, rather
than starting a new key.
Once configparser parses the config file all section names are removed, thus all
keys must have unique names regardless of which INI section they are defined
under. configparser also lowercases all keys, so an option whose name contains
uppercase letters (e.g. `--outputDir`) can't be set from this kind of config
file. A config file that `write_config_file` saved for such an option holds the
lowercased key (`outputdir`), so loading it fails with "unrecognized arguments"
unless `ignore_unknown_config_file_keys=True`, which skips that setting instead.
Also, any keys which have python list syntax are converted to lists by
evaluating them as python code using ast.literal_eval
(https://docs.python.org/3/library/ast.html#ast.literal_eval). To facilitate
this all multi-line values are converted to single-line values. Thus multi-line
string values will have all new-lines converted to spaces. Note, since key-value
pairs that have python dictionary syntax are saved as single-line strings, even
if formatted across multiple lines in the config file, dictionaries can be read
in and converted to valid python dictionaries with PyYAML's safe_load. Example
given below:
```python
# inside your config file (e.g. config.ini)
[section1] # INI sections treated as comments
system1_settings: { # start of multi-line dictionary
'a':True,
'b':[2, 4, 8, 16],
'c':{'start':0, 'stop':1000},
'd':'experiment 32 testing simulation with parameter a on'
} # end of multi-line dictionary value
.......
# in your configargparse setup
import configargparse
import yaml
parser = configargparse.ArgParser(
config_file_parser_class=configargparse.ConfigparserConfigFileParser
)
parser.add_argument('--system1_settings', type=yaml.safe_load)
args = parser.parse_args() # now args.system1 is a valid python dict
```
#### *IniConfigParser* - INI parser with support for sections.
This parser somewhat resembles `ConfigparserConfigFileParser`. It uses configparser and applies the same kind of processing to
values written with python list syntax.
With the following additions:
- Must be created with argument to bind the parser to a list of sections.
- Does not convert multiline strings to single line.
- Optional support for converting multiline strings to list (if `split_ml_text_to_list=True`).
- Optional support for quoting strings in config file
(useful when text must not be converted to list or when text
should contain trailing whitespaces).
This config parser can be used to integrate with `setup.cfg` files.
Example:
```
# 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.
```
If you use `IniConfigParser(sections, split_ml_text_to_list=True)`:
```
# the same rules are applicable with the following changes:
[my-software]
# how to specify a list arg (eg. arg which has action="append")
repeatable-option = # Just enter one value per line (the list literal format can also be used)
https://docs.python.org/3/objects.inv
https://twistedmatrix.com/documents/current/api/objects.inv
# how to specify a multiline text (you have to quote it):
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.
'''
```
Usage:
```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']),
)
...
```
#### *TomlConfigParser* - TOML parser with support for sections.
[TOML](https://github.com/toml-lang/toml/blob/main/toml.md) parser. This config parser can be used to integrate with `pyproject.toml` files.
Requires installation of [toml](https://pypi.org/project/toml/) for Python versions
below 3.11, and for writing a config file out on any version, since the standard
library's `tomllib` can only read.
Example:
```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
# 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.
'''
```
Usage:
```python
import configargparse
parser = configargparse.ArgParser(
default_config_files=['pyproject.toml', 'my_super_tool.toml'],
config_file_parser_class=configargparse.TomlConfigParser(['tool.my_super_tool']),
)
...
```
#### *CompositeConfigParser* - parses more than one config file format.
This parser will successively try to parse the file with each parser, until it succeeds,
else fail showing all encountered error messages.
The following code will make configargparse understand both TOML and INI formats.
Making it easy to integrate in both `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=configargparse.CompositeConfigParser(
[configargparse.TomlConfigParser(my_tool_sections),
configargparse.IniConfigParser(my_tool_sections, split_ml_text_to_list=True)]
),
)
...
```
Note that it's required to put the TOML parser first because the INI syntax basically would accept anything whereas TOML is a bit more strict.
## ArgParser Singletons
To make it easier to configure different modules in an application,
configargparse provides globally-available ArgumentParser instances
via configargparse.get_argument_parser('name') (similar to
logging.getLogger('name')).
Here is an example of an application with a utils module that also
defines and retrieves its own command-line args.
*main.py*
```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.
```
*utils.py*
```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()
```
## Help Formatters
`ArgumentDefaultsRawHelpFormatter` is a new HelpFormatter that both adds
default values AND disables line-wrapping. It can be passed to the constructor:
`ArgParser(.., formatter_class=ArgumentDefaultsRawHelpFormatter)`
## Aliases
The configargparse.ArgumentParser API inherits its class and method
names from argparse and also provides the following shorter alias names for
convenience:
**Class Aliases:**
- `ArgParser` = `ArgumentParser` (create a new instance)
- `Parser` = `ArgumentParser`
**Method Aliases:**
- `p.add(..)` = `p.add_argument(..)`
- `p.add_arg(..)` = `p.add_argument(..)`
- `p.parse(..)` = `p.parse_args(..)`
- `p.parse_known(..)` = `p.parse_known_args(..)`
**Function Aliases (for global singleton):**
- `configargparse.get_arg_parser()` = `configargparse.get_argument_parser()`
- `configargparse.get_parser()` = `configargparse.get_argument_parser()`
- `configargparse.getArgumentParser()` = `configargparse.get_argument_parser()`
- `configargparse.getArgParser()` = `configargparse.get_argument_parser()`
- `configargparse.getParser()` = `configargparse.get_argument_parser()`
- `configargparse.initArgumentParser()` = `configargparse.init_argument_parser()`
**HelpFormatter Aliases:**
- `RawFormatter` = `RawDescriptionHelpFormatter`
- `DefaultsFormatter` = `ArgumentDefaultsHelpFormatter`
- `DefaultsRawFormatter` = `ArgumentDefaultsRawHelpFormatter`
## API Documentation
You can review the generated API Documentation for the `configargparse` module: [HERE](https://bw2.github.io/ConfigArgParse/)
## Design Notes
Unit tests:
tests/test_configargparse.py contains custom unittests for features
specific to this module (such as config file and env-var support), as
well as a hook to load and run argparse unittests (see the built-in
test.test_argparse module) but on configargparse in place of argparse.
This ensures that configargparse will work as a drop in replacement for
argparse in all usecases.
Previously existing modules (PyPI search keywords: config argparse):
- argparse (built-in module Python v2.7+)
- Good:
- fully featured command line parsing
- can read args from files using an easy to understand mechanism
- Bad:
- syntax for specifying config file path is unusual (eg. @file.txt) and not described in the user help message.
- default config file syntax doesn't support comments and is unintuitive (eg. --namevalue)
- no support for environment variables
- ConfArgParse v1.0.15 (https://pypi.python.org/pypi/ConfArgParse)
- Good:
- extends argparse with support for config files parsed by ConfigParser
- clear documentation in README
- Bad:
- config file values are processed using ArgumentParser.set_defaults(..) which means "required" and "choices" are not handled as expected. For example, if you specify a required value in a config file, you still have to specify it again on the command line.
- doesn't work with Python 3 yet
- no unit tests, code not well documented
- appsettings v0.5 (https://pypi.python.org/pypi/appsettings)
- Good:
- supports config file (yaml format) and env_var parsing
- supports config-file-only setting for specifying lists and dicts
- Bad:
- passes in config file and env settings via parse_args namespace param
- tests not finished and don't work with Python 3 (import StringIO)
- argparse_config v0.5.1 (https://pypi.python.org/pypi/argparse_config)
- Good:
- similar features to ConfArgParse v1.0.15
- Bad:
- doesn't work with Python 3 (error during pip install)
- yconf v0.3.2 - (https://pypi.python.org/pypi/yconf) - features and interface not that great
- hieropt v0.3 - (https://pypi.python.org/pypi/hieropt) - doesn't appear to be maintained, couldn't find documentation
- configurati v0.2.3 - (https://pypi.python.org/pypi/configurati)
- Good:
- JSON, YAML, or Python configuration files
- handles rich data structures such as dictionaries
- can group configuration names into sections (like .ini files)
- Bad:
- doesn't work with Python 3
- 2+ years since last release to PyPI
- apparently unmaintained
Design choices:
1. all options must be settable via command line. Having options that
can only be set using config files or env. vars adds complexity to
the API, and is not a useful enough feature since the developer can
split up options into sections and call a section "config file keys",
with command line args that are just "--" plus the config key.
2. config file and env. var settings should be processed by appending
them to the command line (another benefit of #1). This is an
easy-to-implement solution and implicitly takes care of checking that
all "required" args are provided, etc., plus the behavior should be
easy for users to understand.
3. configargparse shouldn't override argparse's
convert_arg_line_to_args method so that all argparse unit tests
can be run on configargparse.
4. in terms of what to allow for config file keys, the "dest" value of
an option can't serve as a valid config key because many options can
have the same dest. Instead, since multiple options can't use the
same long arg (eg. "--long-arg-x"), let the config key be either
"--long-arg-x" or "long-arg-x". This means the developer can allow
only a subset of the command-line args to be specified via config
file (eg. short args like -x would be excluded). Also, that way
config keys are automatically documented whenever the command line
args are documented in the help message.
5. don't force users to put config file settings in the right .ini [sections].
This doesn't have a clear benefit since all options are command-line settable,
and so have a globally unique key anyway.
Enforcing sections just makes things harder for the user and adds complexity to the implementation.
NOTE: This design choice was preventing configargparse from integrating with common Python project
config files like setup.cfg or pyproject.toml,
so additional parser classes were added that parse only a subset of the values defined in INI or
TOML config files.
6. if necessary, config-file-only args can be added later by
implementing a separate add method and using the namespace arg as in
appsettings_v0.5
Relevant sites:
- http://stackoverflow.com/questions/6133517/parse-config-file-environment-and-command-line-arguments-to-get-a-single-coll
- http://tricksntweaks.blogspot.com/2013_05_01_archive.html
- http://www.youtube.com/watch?v=vvCwqHgZJc8#t=35
## Versioning
This software follows [Semantic Versioning](http://semver.org/)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/README.md 0000644 0001751 0001751 00000054701 15270233507 015453 0 ustar 00runner runner # ConfigArgParse
[](https://pypi.python.org/pypi/ConfigArgParse)
[](https://pypi.python.org/pypi/ConfigArgParse)
[](https://pepy.tech/project/configargparse)
[](https://github.com/bw2/ConfigArgParse/actions/workflows/test.yml)
[](https://bw2.github.io/ConfigArgParse/)
## Overview
Applications with more than a handful of user-settable options are best
configured through a combination of command line args, config files,
hard-coded defaults, and in some cases, environment variables.
Python's command line parsing modules such as argparse have very limited
support for config files and environment variables, so this module
extends argparse to add these features.
**API docs:** https://bw2.github.io/ConfigArgParse/
**PyPI:** http://pypi.python.org/pypi/ConfigArgParse
## Install
To install this library, run:
```
pip install ConfigArgParse
```
## Features
- command-line, config file, env var, and default settings can now be
defined, documented, and parsed in one go using a single API (if a
value is specified in more than one way then: command line >
environment variables > config file values > defaults)
- config files can have .ini or .yaml style syntax (eg. key=value or
key: value)
- user can provide a config file via a normal-looking command line arg
(eg. -c path/to/config.txt) rather than the argparse-style @config.txt
- one or more default config file paths can be specified
(eg. `['/etc/bla.conf', '~/.my_config']`)
- all argparse functionality is fully supported, so this module can
serve as a drop-in replacement (verified by argparse unittests).
- env vars and config file keys & syntax are automatically documented
in the -h help message
- new method `print_values()` can report keys & values and where
they were set (eg. command line, env var, config file, or default).
- lite-weight (no 3rd-party library dependencies except (optionally) PyYAML)
- extensible (`ConfigFileParser` can be subclassed to define a new
config file format)
- unittested by running the unittests that came with argparse but on
configargparse
## Example
*config_test.py*:
Script that defines 4 options and a positional arg and then parses and prints the values. Also,
it prints out the help message as well as the string produced by `format_values()` to show
what they look like.
```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
```
*config.txt:*
Since the script above set the config file as required=True, lets create a config file to give it:
```python
# settings for config_test.py
genome = HCMV # cytomegalovirus genome
dbsnp = /data/dbsnp/variants.vcf
```
*command line:*
Now run the script and pass it the config file:
```bash
DBSNP_PATH=/data/dbsnp/variants_v2.vcf python config_test.py --my-config config.txt f1.vcf f2.vcf
```
*output:*
Here is the result:
```bash
Namespace(dbsnp='/data/dbsnp/variants_v2.vcf', genome='HCMV', my_config='config.txt', v=False, vcf=['f1.vcf', 'f2.vcf'])
----------
usage: config_test.py [-h] -c MY_CONFIG --genome GENOME [-v] [-d DBSNP]
vcf [vcf ...]
Args that start with '--' (eg. --genome) can also be set in a config file
(/etc/app/conf.d/*.conf or ~/.my_settings or specified via -c). Config file
syntax allows: key=value, flag=true, stuff=[a,b,c] (for details, see syntax at
https://goo.gl/R74nmi). If an arg is specified in more than one place, then
commandline values override environment variables which override config file
values which override defaults.
positional arguments:
vcf variant file(s)
optional arguments:
-h, --help show this help message and exit
-c MY_CONFIG, --my-config MY_CONFIG
config file path
--genome GENOME path to genome file
-v verbose
-d DBSNP, --dbsnp DBSNP
known variants .vcf [env var: DBSNP_PATH]
----------
Command Line Args: --my-config config.txt f1.vcf f2.vcf
Environment Variables:
DBSNP_PATH: /data/dbsnp/variants_v2.vcf
Config File (config.txt):
genome: HCMV
```
## Special Values
Under the hood, configargparse handles environment variables and config file
values by converting them to their corresponding command line arg. For
example, "key = value" will be processed as if "--key value" was specified
on the command line.
Also, the following special values (whether in a config file or an environment
variable) are handled in a special way to support booleans and lists:
- `key = true` is handled as if "--key" was specified on the command line.
In your python code this key must be defined as a boolean flag
(eg. action="store_true" or similar).
- `key = false` is handled as if "--key" was not specified (or, for an arg
defined with action=argparse.BooleanOptionalAction, as if "--no-key" was
specified). It still counts as setting the key, though, so a `key = true`
from a lower-priority source (eg. a config file, when `key = false` comes
from an environment variable) is ignored.
- `key = [value1, value2, ...]` is handled as if "--key value1 --key value2"
etc. was specified on the command line. In your python code this key must
be defined as a list (eg. action="append").
## Config File Syntax
Only command line args that have a long version (eg. one that starts with '--')
can be set in a config file. For example, "--color" can be set by putting
"color=green" in a config file. The config file syntax depends on the constructor
arg: `config_file_parser_class` which can be set to one of the provided
classes:
- `DefaultConfigFileParser`
- `YAMLConfigFileParser`
- `ConfigparserConfigFileParser`
- `IniConfigParser`
- `TomlConfigParser`
- `CompositeConfigParser`
or to your own subclass of the `ConfigFileParser` abstract class.
#### *DefaultConfigFileParser* - the full range of valid syntax is:
```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]
```
#### *YAMLConfigFileParser* - allows a subset of YAML syntax (http://goo.gl/VgT2DU)
```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
```
#### *ConfigparserConfigFileParser* - allows a subset of python's configparser
module syntax (https://docs.python.org/3.7/library/configparser.html). In
particular the following configparser options are set:
```python
config = configparser.ArgParser(
delimiters=("=",":"),
allow_no_value=False,
comment_prefixes=("#",";"),
inline_comment_prefixes=("#",";"),
strict=True,
empty_lines_in_values=True,
)
```
Because of `empty_lines_in_values=True`, a line indented more than the key above
it continues that key's value, even after a blank line or a comment line, rather
than starting a new key.
Once configparser parses the config file all section names are removed, thus all
keys must have unique names regardless of which INI section they are defined
under. configparser also lowercases all keys, so an option whose name contains
uppercase letters (e.g. `--outputDir`) can't be set from this kind of config
file. A config file that `write_config_file` saved for such an option holds the
lowercased key (`outputdir`), so loading it fails with "unrecognized arguments"
unless `ignore_unknown_config_file_keys=True`, which skips that setting instead.
Also, any keys which have python list syntax are converted to lists by
evaluating them as python code using ast.literal_eval
(https://docs.python.org/3/library/ast.html#ast.literal_eval). To facilitate
this all multi-line values are converted to single-line values. Thus multi-line
string values will have all new-lines converted to spaces. Note, since key-value
pairs that have python dictionary syntax are saved as single-line strings, even
if formatted across multiple lines in the config file, dictionaries can be read
in and converted to valid python dictionaries with PyYAML's safe_load. Example
given below:
```python
# inside your config file (e.g. config.ini)
[section1] # INI sections treated as comments
system1_settings: { # start of multi-line dictionary
'a':True,
'b':[2, 4, 8, 16],
'c':{'start':0, 'stop':1000},
'd':'experiment 32 testing simulation with parameter a on'
} # end of multi-line dictionary value
.......
# in your configargparse setup
import configargparse
import yaml
parser = configargparse.ArgParser(
config_file_parser_class=configargparse.ConfigparserConfigFileParser
)
parser.add_argument('--system1_settings', type=yaml.safe_load)
args = parser.parse_args() # now args.system1 is a valid python dict
```
#### *IniConfigParser* - INI parser with support for sections.
This parser somewhat resembles `ConfigparserConfigFileParser`. It uses configparser and applies the same kind of processing to
values written with python list syntax.
With the following additions:
- Must be created with argument to bind the parser to a list of sections.
- Does not convert multiline strings to single line.
- Optional support for converting multiline strings to list (if `split_ml_text_to_list=True`).
- Optional support for quoting strings in config file
(useful when text must not be converted to list or when text
should contain trailing whitespaces).
This config parser can be used to integrate with `setup.cfg` files.
Example:
```
# 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.
```
If you use `IniConfigParser(sections, split_ml_text_to_list=True)`:
```
# the same rules are applicable with the following changes:
[my-software]
# how to specify a list arg (eg. arg which has action="append")
repeatable-option = # Just enter one value per line (the list literal format can also be used)
https://docs.python.org/3/objects.inv
https://twistedmatrix.com/documents/current/api/objects.inv
# how to specify a multiline text (you have to quote it):
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.
'''
```
Usage:
```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']),
)
...
```
#### *TomlConfigParser* - TOML parser with support for sections.
[TOML](https://github.com/toml-lang/toml/blob/main/toml.md) parser. This config parser can be used to integrate with `pyproject.toml` files.
Requires installation of [toml](https://pypi.org/project/toml/) for Python versions
below 3.11, and for writing a config file out on any version, since the standard
library's `tomllib` can only read.
Example:
```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
# 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.
'''
```
Usage:
```python
import configargparse
parser = configargparse.ArgParser(
default_config_files=['pyproject.toml', 'my_super_tool.toml'],
config_file_parser_class=configargparse.TomlConfigParser(['tool.my_super_tool']),
)
...
```
#### *CompositeConfigParser* - parses more than one config file format.
This parser will successively try to parse the file with each parser, until it succeeds,
else fail showing all encountered error messages.
The following code will make configargparse understand both TOML and INI formats.
Making it easy to integrate in both `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=configargparse.CompositeConfigParser(
[configargparse.TomlConfigParser(my_tool_sections),
configargparse.IniConfigParser(my_tool_sections, split_ml_text_to_list=True)]
),
)
...
```
Note that it's required to put the TOML parser first because the INI syntax basically would accept anything whereas TOML is a bit more strict.
## ArgParser Singletons
To make it easier to configure different modules in an application,
configargparse provides globally-available ArgumentParser instances
via configargparse.get_argument_parser('name') (similar to
logging.getLogger('name')).
Here is an example of an application with a utils module that also
defines and retrieves its own command-line args.
*main.py*
```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.
```
*utils.py*
```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()
```
## Help Formatters
`ArgumentDefaultsRawHelpFormatter` is a new HelpFormatter that both adds
default values AND disables line-wrapping. It can be passed to the constructor:
`ArgParser(.., formatter_class=ArgumentDefaultsRawHelpFormatter)`
## Aliases
The configargparse.ArgumentParser API inherits its class and method
names from argparse and also provides the following shorter alias names for
convenience:
**Class Aliases:**
- `ArgParser` = `ArgumentParser` (create a new instance)
- `Parser` = `ArgumentParser`
**Method Aliases:**
- `p.add(..)` = `p.add_argument(..)`
- `p.add_arg(..)` = `p.add_argument(..)`
- `p.parse(..)` = `p.parse_args(..)`
- `p.parse_known(..)` = `p.parse_known_args(..)`
**Function Aliases (for global singleton):**
- `configargparse.get_arg_parser()` = `configargparse.get_argument_parser()`
- `configargparse.get_parser()` = `configargparse.get_argument_parser()`
- `configargparse.getArgumentParser()` = `configargparse.get_argument_parser()`
- `configargparse.getArgParser()` = `configargparse.get_argument_parser()`
- `configargparse.getParser()` = `configargparse.get_argument_parser()`
- `configargparse.initArgumentParser()` = `configargparse.init_argument_parser()`
**HelpFormatter Aliases:**
- `RawFormatter` = `RawDescriptionHelpFormatter`
- `DefaultsFormatter` = `ArgumentDefaultsHelpFormatter`
- `DefaultsRawFormatter` = `ArgumentDefaultsRawHelpFormatter`
## API Documentation
You can review the generated API Documentation for the `configargparse` module: [HERE](https://bw2.github.io/ConfigArgParse/)
## Design Notes
Unit tests:
tests/test_configargparse.py contains custom unittests for features
specific to this module (such as config file and env-var support), as
well as a hook to load and run argparse unittests (see the built-in
test.test_argparse module) but on configargparse in place of argparse.
This ensures that configargparse will work as a drop in replacement for
argparse in all usecases.
Previously existing modules (PyPI search keywords: config argparse):
- argparse (built-in module Python v2.7+)
- Good:
- fully featured command line parsing
- can read args from files using an easy to understand mechanism
- Bad:
- syntax for specifying config file path is unusual (eg. @file.txt) and not described in the user help message.
- default config file syntax doesn't support comments and is unintuitive (eg. --namevalue)
- no support for environment variables
- ConfArgParse v1.0.15 (https://pypi.python.org/pypi/ConfArgParse)
- Good:
- extends argparse with support for config files parsed by ConfigParser
- clear documentation in README
- Bad:
- config file values are processed using ArgumentParser.set_defaults(..) which means "required" and "choices" are not handled as expected. For example, if you specify a required value in a config file, you still have to specify it again on the command line.
- doesn't work with Python 3 yet
- no unit tests, code not well documented
- appsettings v0.5 (https://pypi.python.org/pypi/appsettings)
- Good:
- supports config file (yaml format) and env_var parsing
- supports config-file-only setting for specifying lists and dicts
- Bad:
- passes in config file and env settings via parse_args namespace param
- tests not finished and don't work with Python 3 (import StringIO)
- argparse_config v0.5.1 (https://pypi.python.org/pypi/argparse_config)
- Good:
- similar features to ConfArgParse v1.0.15
- Bad:
- doesn't work with Python 3 (error during pip install)
- yconf v0.3.2 - (https://pypi.python.org/pypi/yconf) - features and interface not that great
- hieropt v0.3 - (https://pypi.python.org/pypi/hieropt) - doesn't appear to be maintained, couldn't find documentation
- configurati v0.2.3 - (https://pypi.python.org/pypi/configurati)
- Good:
- JSON, YAML, or Python configuration files
- handles rich data structures such as dictionaries
- can group configuration names into sections (like .ini files)
- Bad:
- doesn't work with Python 3
- 2+ years since last release to PyPI
- apparently unmaintained
Design choices:
1. all options must be settable via command line. Having options that
can only be set using config files or env. vars adds complexity to
the API, and is not a useful enough feature since the developer can
split up options into sections and call a section "config file keys",
with command line args that are just "--" plus the config key.
2. config file and env. var settings should be processed by appending
them to the command line (another benefit of #1). This is an
easy-to-implement solution and implicitly takes care of checking that
all "required" args are provided, etc., plus the behavior should be
easy for users to understand.
3. configargparse shouldn't override argparse's
convert_arg_line_to_args method so that all argparse unit tests
can be run on configargparse.
4. in terms of what to allow for config file keys, the "dest" value of
an option can't serve as a valid config key because many options can
have the same dest. Instead, since multiple options can't use the
same long arg (eg. "--long-arg-x"), let the config key be either
"--long-arg-x" or "long-arg-x". This means the developer can allow
only a subset of the command-line args to be specified via config
file (eg. short args like -x would be excluded). Also, that way
config keys are automatically documented whenever the command line
args are documented in the help message.
5. don't force users to put config file settings in the right .ini [sections].
This doesn't have a clear benefit since all options are command-line settable,
and so have a globally unique key anyway.
Enforcing sections just makes things harder for the user and adds complexity to the implementation.
NOTE: This design choice was preventing configargparse from integrating with common Python project
config files like setup.cfg or pyproject.toml,
so additional parser classes were added that parse only a subset of the values defined in INI or
TOML config files.
6. if necessary, config-file-only args can be added later by
implementing a separate add method and using the namespace arg as in
appsettings_v0.5
Relevant sites:
- http://stackoverflow.com/questions/6133517/parse-config-file-environment-and-command-line-arguments-to-get-a-single-coll
- http://tricksntweaks.blogspot.com/2013_05_01_archive.html
- http://www.youtube.com/watch?v=vvCwqHgZJc8#t=35
## Versioning
This software follows [Semantic Versioning](http://semver.org/)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/SECURITY.md 0000644 0001751 0001751 00000002016 15270233507 015755 0 ustar 00runner runner # Security Policy
## Supported versions
Security fixes are released for the latest version only. If you are running an older
version, please upgrade before reporting an issue, in case it is already fixed.
## Reporting a vulnerability
Please report security issues privately, not as a public GitHub issue.
Use GitHub's private vulnerability reporting:
https://github.com/bw2/ConfigArgParse/security/advisories/new
That form is private to the maintainers.
Helpful things to include:
- the version of ConfigArgParse you tested, and the Python version
- a short script that reproduces the problem, ideally one file
- what an attacker would need to control (a config file, an environment variable, command
line arguments) and what they gain
## What to expect
This is a small project maintained in spare time, so please allow a few days for a first
reply. If a report is valid, the usual sequence is a fix on `master`, a release to PyPI, and
a published GitHub security advisory crediting you unless you would rather not be named.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/apidocs.sh 0000755 0001751 0001751 00000003274 15270233507 016154 0 ustar 00runner runner #!/bin/bash
# This bash script builds the API documentation for ConfigArgParse.
# Resolve source directory path. From https://stackoverflow.com/questions/59895/how-to-get-the-source-directory-of-a-bash-script-from-within-the-script-itself/246128#246128
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
cd $SCRIPT_DIR
# Stop if errors
set -euo pipefail
IFS=$'\n\t,'
# Figure the project version
project_version="$(python3 setup.py -V)"
# Figure commit ref
git_sha="$(git rev-parse HEAD)"
if git describe --exact-match --tags > /dev/null 2>&1 ; then
git_sha="$(git describe --exact-match --tags)"
fi
# Init output folder
docs_folder="./apidocs/"
rm -rf "${docs_folder}"
mkdir -p "${docs_folder}"
# We generate the docs for the argparse module too, such that we can document
# the methods inherited from argparse.ArgumentParser, not only the methods that configargparse overrides.
# And it help to have a better vision of the whole thing also.
curl https://raw.githubusercontent.com/python/cpython/3.9/Lib/argparse.py > ./argparse.py
echo "__docformat__ = 'restructuredtext'" >> ./argparse.py
# Delete the file when the script exits
trap "rm -f ./argparse.py" EXIT
pydoctor \
--project-name="ConfigArgParse ${project_version}" \
--project-url="https://github.com/bw2/ConfigArgParse" \
--html-viewsource-base="https://github.com/bw2/ConfigArgParse/tree/${git_sha}" \
--template-dir=./apidocs_templates \
--intersphinx=https://docs.python.org/3/objects.inv \
--make-html \
--quiet \
--project-base-dir=.\
--docformat=google \
--html-output="${docs_folder}" \
./argparse.py ./configargparse.py || true
echo "API docs generated in ${docs_folder}"
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7550256
configargparse-1.9.0/apidocs_templates/ 0000755 0001751 0001751 00000000000 15270233512 017661 5 ustar 00runner runner ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9298978
configargparse-1.9.0/apidocs_templates/extra.css 0000644 0001751 0001751 00000000421 15270233507 021517 0 ustar 00runner runner /* The project name in the header links to the GitHub repo, so color it like a link */
.navbar-brand a.projecthome {
color: #337ab7;
}
.navbar-brand a.projecthome:hover {
color: #23527c;
}
.github-link-bar {
padding: 5px 15px 0 15px;
text-align: right;
}
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9304025
configargparse-1.9.0/apidocs_templates/header.html 0000644 0001751 0001751 00000000161 15270233507 022001 0 ustar 00runner runner
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9304025
configargparse-1.9.0/configargparse.py 0000644 0001751 0001751 00000322673 15270233507 017546 0 ustar 00runner runner """
A drop-in replacement for `argparse` that allows options to also be set via config files and/or environment variables.
:see: `configargparse.ArgumentParser`, `configargparse.add_argument`
"""
import argparse
import ast
import configparser
import csv
import functools
import json
import glob
import os
import re
import sys
import types
from collections import OrderedDict
import textwrap
import warnings
from io import StringIO
ACTION_TYPES_THAT_DONT_NEED_A_VALUE = [
argparse._StoreTrueAction,
argparse._StoreFalseAction,
argparse._CountAction,
argparse._StoreConstAction,
argparse._AppendConstAction,
]
if sys.version_info >= (3, 9):
ACTION_TYPES_THAT_DONT_NEED_A_VALUE.append(argparse.BooleanOptionalAction)
is_boolean_optional_action = lambda action: isinstance(
action, argparse.BooleanOptionalAction
)
else:
is_boolean_optional_action = lambda action: False
ACTION_TYPES_THAT_DONT_NEED_A_VALUE = tuple(ACTION_TYPES_THAT_DONT_NEED_A_VALUE)
# global ArgumentParser instances
_parsers = {}
def init_argument_parser(name=None, **kwargs):
"""Creates a global ArgumentParser instance with the given name,
passing any args other than "name" to the ArgumentParser constructor.
This instance can then be retrieved using get_argument_parser(..)
"""
if name is None:
name = "default"
if name in _parsers:
raise ValueError(
(
"kwargs besides 'name' can only be passed in the"
" first time. '%s' ArgumentParser already exists: %s"
)
% (name, _parsers[name])
)
kwargs.setdefault("formatter_class", argparse.ArgumentDefaultsHelpFormatter)
kwargs.setdefault("conflict_handler", "resolve")
_parsers[name] = ArgumentParser(**kwargs)
def get_argument_parser(name=None, **kwargs):
"""Returns the global ArgumentParser instance with the given name. The 1st
time this function is called, a new ArgumentParser instance will be created
for the given name, and any args other than "name" will be passed on to the
ArgumentParser constructor.
"""
if name is None:
name = "default"
if len(kwargs) > 0 or name not in _parsers:
init_argument_parser(name, **kwargs)
return _parsers[name]
class ArgumentDefaultsRawHelpFormatter(
argparse.ArgumentDefaultsHelpFormatter,
argparse.RawTextHelpFormatter,
argparse.RawDescriptionHelpFormatter,
):
"""HelpFormatter that adds default values AND doesn't do line-wrapping"""
pass
class ConfigFileParser(object):
"""This abstract class can be extended to add support for new config file
formats"""
def get_syntax_description(self):
"""Returns a string describing the config file syntax."""
raise NotImplementedError("get_syntax_description(..) not implemented")
def parse(self, stream):
"""Parses the keys and values from a config file.
NOTE: For keys that were specified to configargparse as
action="store_true" or "store_false", the config file value must be
one of: "yes", "no", "on", "off", "true", "false". Otherwise an error will be raised.
Args:
stream (io.IOBase): A config file input stream (such as an open file object).
Returns:
OrderedDict: Items where the keys are strings and the
values are either strings or lists (eg. to support config file
formats like YAML which allow lists).
"""
raise NotImplementedError("parse(..) not implemented")
def serialize(self, items):
"""Does the inverse of config parsing by taking parsed values and
converting them back to a string representing config file contents.
Args:
items: an OrderedDict of items to be converted to the config file
format. Keys should be strings, and values should be either strings
or lists.
Returns:
Contents of config file as a string
"""
raise NotImplementedError("serialize(..) not implemented")
class _WriteOutConfigFileActionMixin(object):
"""Remembers the path this arg was given, on the parser that parsed it.
The path can't just be read back out of the parsed namespace once parsing
finishes: another arg sharing this one's dest could have put a value there,
from a config file or anywhere else, and writing a config file overwrites
the path it is given. Recording it as the arg is parsed means only this
arg decides where that write goes.
add_argument() puts this over whichever store action the program asked for,
so an arg that does something of its own with the path still records it.
"""
def __call__(self, parser, namespace, values, option_string=None):
super(_WriteOutConfigFileActionMixin, self).__call__(
parser, namespace, values, option_string
)
# take the value back off the namespace: the action just put it there,
# and a store action of the program's own may have changed it on the
# way (expanding a '~', say). Keyed by the action so that repeating the
# arg replaces the path rather than adding a second one.
# a parser that isn't a ConfigArgParse one has nowhere to record it,
# and doesn't write config files either, so there is nothing to record
if hasattr(parser, "_write_out_config_file_paths"):
parser._write_out_config_file_paths[id(self)] = getattr(
namespace, self.dest, values
)
class ConfigFileParserException(Exception):
"""Raised when config file parsing failed."""
class ConfigFileParserMissingDependency(ConfigFileParserException):
"""Raised when an optional dependency is missing."""
class DefaultConfigFileParser(ConfigFileParser):
"""
Based on a simplified subset of INI and YAML formats. Here is the
supported syntax
.. code::
# 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]
"""
def get_syntax_description(self):
msg = (
"Config file syntax allows: key=value, flag=true, stuff=[a,b,c] "
"(for details, see syntax at https://goo.gl/R74nmi)."
)
return msg
def parse(self, stream):
# see ConfigFileParser.parse docstring
items = OrderedDict()
for i, line in enumerate(stream):
line = line.strip()
if not line or line[0] in ["#", ";", "["] or line.startswith("---"):
continue
match = re.match(
r"^(?P[^:=;#\s]+)\s*"
r'(?:(?P[:=\s])\s*([\'"]?)(?P.+?)?\3)?'
r"\s*(?:\s[;#]\s*(?P.*?)\s*)?$",
line,
)
if match:
key = match.group("key")
equal = match.group("equal")
value = match.group("value")
comment = match.group("comment")
if value is None and equal is not None and equal != " ":
value = ""
elif value is None:
value = "true"
if value.startswith("[") and value.endswith("]"):
# handle special case of k=[1,2,3] or other json-like syntax
try:
value = json.loads(value)
except Exception as e:
# for backward compatibility with legacy format (eg. where config value is [a, b, c] instead of proper json ["a", "b", "c"]
value = [elem.strip() for elem in value[1:-1].split(",")]
items[key] = value
else:
raise ConfigFileParserException(
"Unexpected line {} in {}: {}".format(
i, getattr(stream, "name", "stream"), line
)
)
return items
def serialize(self, items):
# see ConfigFileParser.serialize docstring
r = StringIO()
for key, value in items.items():
if isinstance(value, list):
# handle special case of lists
value = "[" + ", ".join(map(str, value)) + "]"
else:
# render it the way this has always rendered it: str() differs
# for an Enum on Python before 3.11
value = "{}".format(value)
# this format puts one key on each line, so a newline in a key or a
# value would silently turn into extra keys when the file is read
# back in (see parse() above). There's no way to quote it, so say so
# instead of writing a file that means something else.
for field in (str(key), value):
if "\n" in field or "\r" in field:
raise ValueError(
"Config file values can't contain newlines, so {} = {} "
"can't be written out in this config file format. Use a "
"config_file_parser_class that supports multi-line "
"values, such as YAMLConfigFileParser.".format(key, value)
)
r.write("{} = {}\n".format(key, value))
return r.getvalue()
def _keep_literal_or_convert_to_str(value):
"""Return a list element as it should be written into a list repr.
Args:
value: an element of a list value.
Returns:
object: the value unchanged if ``ast.literal_eval`` of its repr gives
it back, otherwise ``str(value)`` (e.g. for a Path, or inf).
"""
try:
if ast.literal_eval(repr(value)) == value:
return value
except (ValueError, SyntaxError):
pass
return str(value)
class ConfigparserConfigFileParser(ConfigFileParser):
"""parses INI files using pythons configparser."""
def get_syntax_description(self):
msg = """Uses configparser module to parse an INI file which allows multi-line
values.
Allowed syntax is that for a ConfigParser with the following options:
delimiters = ("=", ":")
allow_no_value = False,
comment_prefixes = ("#", ";")
inline_comment_prefixes = ("#", ";")
strict = True
empty_lines_in_values = True
See https://docs.python.org/3/library/configparser.html for details.
Note: INI file sections names are still treated as comments.
Settings in a [DEFAULT] section are also read. Keys are lowercased, so
an option whose name has uppercase letters can't be set this way, and a
saved config file that contains one fails to load unless
ignore_unknown_config_file_keys=True.
"""
return msg
def parse(self, stream):
# see ConfigFileParser.parse docstring
# parse with configparser to allow multi-line values
config = configparser.ConfigParser(
delimiters=("=", ":"),
allow_no_value=False,
comment_prefixes=("#", ";"),
inline_comment_prefixes=("#", ";"),
strict=True,
# a line indented more than the key above it continues that key's
# value even after a blank or comment line, rather than starting a
# new key, so a value saved with a blank line in it by an earlier
# version of serialize() can't turn into extra keys
empty_lines_in_values=True,
)
try:
config.read_string(stream.read())
except Exception as e:
raise ConfigFileParserException("Couldn't parse config file: %s" % e)
# convert to dict and remove INI section names
result = OrderedDict()
for section in config.sections() or [configparser.DEFAULTSECT]:
# configparser expands %(name)s references while reading values,
# so a stray % fails here rather than in read_string() above
try:
section_items = list(config[section].items())
except configparser.InterpolationError as e:
# name only the key, since configparser's own message shows the
# value, which may be a secret ("from None" keeps that message
# out of tracebacks too). e.option is the key being read, and the
# problem may be in a value its %(name)s references pull in.
if isinstance(e, configparser.InterpolationDepthError):
problem = (
"its %(name)s references refer back to it or are nested "
"too deeply"
)
elif isinstance(e, configparser.InterpolationMissingOptionError):
problem = (
"it, or a value it references, has a %(name)s reference "
"to a key that isn't in the same section or in [DEFAULT]. "
"Write %% for a literal %"
)
else:
problem = (
"it, or a value it references, has a '%' that isn't '%%' "
"or a valid %(name)s reference. Write %% for a literal %"
)
raise ConfigFileParserException(
"Couldn't parse config file value for {}: {}.".format(
e.option, problem
)
) from None
for k, v in section_items:
multiLine2SingleLine = v.replace("\n", " ").replace("\r", " ")
# handle special case for lists
if "[" in multiLine2SingleLine and "]" in multiLine2SingleLine:
# ensure not a dict with a list value
prelist_string = multiLine2SingleLine.split("[")[0]
if "{" not in prelist_string:
try:
result[k] = ast.literal_eval(multiLine2SingleLine)
except (ValueError, SyntaxError) as e:
raise ConfigFileParserException(
"Error evaluating list: "
+ str(e)
+ ". Put quotes around your text if it's meant to be a string."
) from e
else:
result[k] = multiLine2SingleLine
else:
result[k] = multiLine2SingleLine
return result
def serialize(self, items):
# see ConfigFileParser.serialize docstring
config = configparser.ConfigParser(
allow_no_value=False,
inline_comment_prefixes=("#",),
strict=True,
empty_lines_in_values=False,
)
# write each value so that parse() reads back the same value, except
# that configparser strips whitespace from the start and end of a value
values = OrderedDict()
for key, value in items.items():
if isinstance(value, list):
# parse() can only evaluate the repr of literals, so write an
# element that isn't one (e.g. a Path) as its str(). Keep the
# other elements as they are, because
# convert_item_to_command_line_arg() passes some inner lists on
# whole, as str() of the list (e.g. for nargs="+" with
# type=json.loads, or for an unknown key). A tuple is written as
# its str() below, as DefaultConfigFileParser writes it, so it
# reads back as that string, which e.g. type=ast.literal_eval
# turns back into the tuple.
value = str(
[
(
[_keep_literal_or_convert_to_str(e) for e in elem]
if isinstance(elem, list)
else _keep_literal_or_convert_to_str(elem)
)
for elem in value
]
)
is_python_literal = True
else:
# parse() turns newlines into spaces anyway, and a lone \r in a
# value would be read back as the start of a new key, so write
# the spaces here
value = str(value).replace("\n", " ").replace("\r", " ")
# parse() evaluates a value that looks like a list (same test as
# in parse() above), so quote such a string to read it back as a
# string
is_python_literal = (
"[" in value and "]" in value and "{" not in value.split("[")[0]
)
if is_python_literal:
value = repr(value)
# parse() reads a "#" or ";" after a space as the start of a comment.
if is_python_literal:
# In a list repr, or a string quoted with repr(), they can only
# be inside a string literal, so write them as escape codes,
# which parse()'s ast.literal_eval decodes back.
value = value.replace("#", "\\x23").replace(";", "\\x3b")
elif re.search(r"\s[#;]", value):
# configparser can't quote a plain string, so warn that the
# value will read back cut short. The warning names only the
# key, since the value may be a secret. One at the start of a
# value is fine, since the value is written right after the "="
# (see below).
warnings.warn(
"The value of {} contains a '#' or ';' after a space, which "
"this config file format reads back as the start of a "
"comment, so the saved value will be cut short there. Use a "
"config_file_parser_class that can quote values, such as "
"YAMLConfigFileParser, to save it in full.".format(key)
)
# parse() expands %(name)s references, so escape every %
values[key] = value.replace("%", "%%")
config.read_dict({"DEFAULT": values})
stream = StringIO()
# "key=value" rather than "key = value", so that a value starting with
# "#" or ";" isn't read back as a comment
config.write(stream, space_around_delimiters=False)
stream.seek(0)
return stream.read()
class YAMLConfigFileParser(ConfigFileParser):
"""Parses YAML config files. Depends on the PyYAML module.
https://pypi.python.org/pypi/PyYAML
"""
def get_syntax_description(self):
msg = (
"The config file uses YAML syntax and must represent a YAML "
"'mapping' (for details, see http://learn.getgrav.org/advanced/yaml)."
)
return msg
def _load_yaml(self):
"""lazy-import PyYAML so that configargparse doesn't have to depend
on it unless this parser is used."""
try:
import yaml
except ImportError:
raise ConfigFileParserMissingDependency(
"Could not import yaml. "
"It can be installed by running 'pip install PyYAML'"
)
try:
from yaml import CSafeLoader as SafeLoader
from yaml import CDumper as Dumper
except ImportError:
from yaml import SafeLoader
from yaml import Dumper
return yaml, SafeLoader, Dumper
def parse(self, stream):
# see ConfigFileParser.parse docstring
yaml, SafeLoader, _ = self._load_yaml()
try:
parsed_obj = yaml.load(stream, Loader=SafeLoader)
except Exception as e:
raise ConfigFileParserException("Couldn't parse config file: %s" % e)
if not isinstance(parsed_obj, dict):
raise ConfigFileParserException(
"The config file doesn't appear to "
"contain 'key: value' pairs (aka. a YAML mapping). "
"yaml.load('%s') returned type '%s' instead of 'dict'."
% (getattr(stream, "name", "stream"), type(parsed_obj).__name__)
)
result = OrderedDict()
for key, value in parsed_obj.items():
if isinstance(value, list):
result[key] = value
elif value is None:
pass
else:
result[key] = str(value)
return result
def serialize(self, items, default_flow_style=False):
# see ConfigFileParser.serialize docstring
# lazy-import so there's no dependency on yaml unless this class is used
yaml, _, Dumper = self._load_yaml()
# it looks like ordering can't be preserved: http://pyyaml.org/ticket/29
items = dict(items)
return yaml.dump(items, default_flow_style=default_flow_style, Dumper=Dumper)
"""
Provides `configargparse.ConfigFileParser` classes to parse ``TOML`` and ``INI`` files with **mandatory** support for sections.
Useful to integrate configuration into project files like ``pyproject.toml`` or ``setup.cfg``.
`TomlConfigParser` usage:
>>> TomlParser = TomlConfigParser(['tool.my_super_tool']) # Simple TOML parser.
>>> parser = ArgumentParser(..., default_config_files=['./pyproject.toml'], config_file_parser_class=TomlParser)
`IniConfigParser` works the same way (also it optionaly convert multiline strings to list with argument ``split_ml_text_to_list``).
`CompositeConfigParser` usage:
>>> MY_CONFIG_SECTIONS = ['tool.my_super_tool', 'tool:my_super_tool', 'my_super_tool']
>>> TomlParser = TomlConfigParser(MY_CONFIG_SECTIONS)
>>> IniParser = IniConfigParser(MY_CONFIG_SECTIONS, split_ml_text_to_list=True)
>>> MixedParser = CompositeConfigParser([TomlParser, IniParser]) # This parser supports both TOML and INI formats.
>>> parser = ArgumentParser(..., default_config_files=['./pyproject.toml', 'setup.cfg', 'my_super_tool.ini'], config_file_parser_class=MixedParser)
"""
# I did not invented these regex, just put together some stuff from:
# - https://stackoverflow.com/questions/11859442/how-to-match-string-in-quotes-using-regex
# - and https://stackoverflow.com/a/41005190
_QUOTED_STR_REGEX = re.compile(r"(^\"(?:\\.|[^\"\\])*\"$)|" r"(^\'(?:\\.|[^\'\\])*\'$)")
_TRIPLE_QUOTED_STR_REGEX = re.compile(
r"(^\"\"\"(\s+)?(([^\"]|\"([^\"]|\"[^\"]))*(\"\"?)?)?(\s+)?(?:\\.|[^\"\\])?\"\"\"$)|"
# Unescaped quotes at the end of a string generates
# "SyntaxError: EOL while scanning string literal",
# so we don't account for those kind of strings as quoted.
r"(^\'\'\'(\s+)?(([^\']|\'([^\']|\'[^\']))*(\'\'?)?)?(\s+)?(?:\\.|[^\'\\])?\'\'\'$)",
flags=re.DOTALL,
)
@functools.lru_cache(maxsize=256, typed=True)
def is_quoted(text, triple=True):
"""
Detect whether a string is a quoted representation.
:param triple: Also match tripple quoted strings.
"""
return bool(_QUOTED_STR_REGEX.match(text)) or (
triple and bool(_TRIPLE_QUOTED_STR_REGEX.match(text))
)
def unquote_str(text, triple=True):
"""
Unquote a maybe quoted string representation.
If the string is not detected as being a quoted representation, it returns the same string as passed.
It supports all kinds of python quotes: ``\"\"\"``, ``'''``, ``"`` and ``'``.
:param triple: Also unquote tripple quoted strings.
:raises ValueError: If the string is detected as beeing quoted but literal_eval() fails to evaluate it as string.
This would be a bug in the regex.
"""
if is_quoted(text, triple=triple):
try:
s = ast.literal_eval(text)
assert isinstance(s, str)
except Exception as e:
raise ValueError(
f"Error trying to unquote the quoted string: {text}: {e}"
) from e
return s
return text
def parse_toml_section_name(section_name):
"""
Parse a TOML section name to a sequence of strings.
The following names are all valid:
.. python::
"a.b.c" # this is best practice -> returns ("a", "b", "c")
" d.e.f " # same as [d.e.f] -> returns ("d", "e", "f")
" g . h . i " # same as [g.h.i] -> returns ("g", "h", "i")
' j . "ʞ" . "l" ' # same as [j."ʞ"."l"], double or simple quotes here are supported. -> returns ("j", "ʞ", "l")
"""
section = []
for row in csv.reader([section_name], delimiter="."):
for a in row:
section.append(unquote_str(a.strip(), triple=False))
return tuple(section)
def get_toml_section(data, section):
"""
Given some TOML data (as loaded with toml.load()), returns the requested section of the data.
Returns ``None`` if the section is not found.
"""
sections = parse_toml_section_name(section) if isinstance(section, str) else section
itemdata = data.get(sections[0])
if not itemdata:
return None
sections = sections[1:]
if sections:
return get_toml_section(itemdata, sections)
else:
if not isinstance(itemdata, dict):
return None
return itemdata
class TomlConfigParser(ConfigFileParser):
"""
Create a TOML parser bounded to the list of provided sections.
Example::
# 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
# 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.
'''
Note that the config file fragment above is also valid for the `IniConfigParser` class and would be parsed the same manner.
Thought, any valid TOML config file will not be necessarly parsable with `IniConfigParser` (INI files must be rigorously indented whereas TOML files).
See the `TOML specification `_ for details.
"""
def __init__(self, sections):
"""
:param sections: The section names bounded to the new parser.
"""
super().__init__()
self.sections = sections
def __call__(self):
return self
def parse(self, stream):
"""Parses the keys and values from a TOML config file."""
# Use tomllib (Python 3.11+) if available, otherwise fall back to toml package
try:
import tomllib as toml
except ImportError:
try:
import toml
except ImportError as e:
raise ConfigFileParserMissingDependency(
"Could not import toml or tomllib. "
"toml can be installed by running 'pip install toml'"
) from e
# tomllib.load() requires binary mode, so use loads() for stream compatibility
try:
content = stream.read()
# If content is bytes, decode it; if string, use as-is
if isinstance(content, bytes):
content = content.decode("utf-8")
config = toml.loads(content)
except Exception as e:
raise ConfigFileParserException("Couldn't parse TOML file: %s" % e)
# convert to dict and filter based on section names
result = OrderedDict()
for section in self.sections:
data = get_toml_section(config, section)
if data:
# Seems a little weird, but anything that is not a list is converted to string,
# It will be converted back to boolean, int or whatever after.
# Because config values are still passed to argparser for computation.
for key, value in data.items():
if isinstance(value, list):
result[key] = value
elif value is None:
pass
else:
result[key] = str(value)
return result
def get_syntax_description(self):
return (
"Config file syntax is Tom's Obvious, Minimal Language. "
"See https://github.com/toml-lang/toml/blob/v0.5.0/README.md for details."
)
def serialize(self, items):
"""Serialize items to TOML format with section support.
Note: Requires the 'toml' package for serialization (pip install toml).
Python 3.11's tomllib only supports reading, not writing.
"""
# lazy-import to avoid dependency unless class is used
try:
import toml
except ImportError:
raise ConfigFileParserMissingDependency(
"The 'toml' package is required for TOML serialization. "
"Install it with: pip install toml"
)
# Put items in the first configured section
if not self.sections:
# No sections configured, serialize as flat TOML
return toml.dumps(dict(items))
# Create nested dict structure for section
section_name = self.sections[0]
sections = parse_toml_section_name(section_name)
# Build nested dict from section path
result = {}
current = result
for i, section in enumerate(sections[:-1]):
current[section] = {}
current = current[section]
current[sections[-1]] = dict(items)
return toml.dumps(result)
class IniConfigParser(ConfigFileParser):
"""
Create a INI parser bounded to the list of provided sections.
Optionaly convert multiline strings to list.
Example (if split_ml_text_to_list=False)::
# this is a comment
; also a comment
[my-software]
# 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.
Example (if split_ml_text_to_list=True)::
# the same rules are applicable with the following changes:
[my-software]
# how to specify a list arg (eg. arg which has action="append")
repeatable-option = # Just enter one value per line (the list literal format can also be used)
https://docs.python.org/3/objects.inv
https://twistedmatrix.com/documents/current/api/objects.inv
# how to specify a multiline text (you have to quote it):
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.
'''
"""
def __init__(self, sections, split_ml_text_to_list):
"""
:param sections: The section names bounded to the new parser.
:param split_ml_text_to_list: Whether to convert multiline strings to list
"""
super().__init__()
self.sections = sections
self.split_ml_text_to_list = split_ml_text_to_list
def __call__(self):
return self
def parse(self, stream):
"""Parses the keys and values from an INI config file."""
# parse with configparser to allow multi-line values
config = configparser.ConfigParser()
try:
config.read_string(stream.read())
except Exception as e:
raise ConfigFileParserException("Couldn't parse INI file: %s" % e)
# convert to dict and filter based on INI section names
result = OrderedDict()
for section in config.sections() + [configparser.DEFAULTSECT]:
if section not in self.sections:
continue
for k, v in config[section].items():
strip_v = v.strip()
if not strip_v:
# ignores empty values, anyway allow_no_value=False by default so this should not happend.
continue
# evaluate lists
if strip_v.startswith("[") and strip_v.endswith("]"):
try:
result[k] = ast.literal_eval(strip_v)
except (ValueError, SyntaxError) as e:
# error evaluating object
raise ConfigFileParserException(
"Error evaluating list: "
+ str(e)
+ ". Put quotes around your text if it's meant to be a string."
) from e
else:
if is_quoted(strip_v):
# evaluate quoted string
try:
result[k] = unquote_str(strip_v)
except ValueError as e:
# error unquoting string
raise ConfigFileParserException(str(e)) from e
# split multi-line text into list of strings if split_ml_text_to_list is enabled.
elif self.split_ml_text_to_list and "\n" in v.rstrip("\n"):
try:
result[k] = [
unquote_str(i) for i in strip_v.split("\n") if i
]
except ValueError as e:
# error unquoting string
raise ConfigFileParserException(str(e)) from e
else:
result[k] = v
return result
def get_syntax_description(self):
msg = (
"Uses configparser module to parse an INI file which allows multi-line values. "
"See https://docs.python.org/3/library/configparser.html for details. "
"This parser includes support for quoting strings literal as well as python list syntax evaluation. "
)
if self.split_ml_text_to_list:
msg += (
"Alternatively lists can be constructed with a plain multiline string, "
"each non-empty line will be converted to a list item."
)
return msg
def serialize(self, items):
"""Serialize items to INI format with section support."""
config = configparser.ConfigParser()
# Use the first configured section
section_name = self.sections[0] if self.sections else "DEFAULT"
# Add section if not DEFAULT
if section_name != "DEFAULT" and section_name != configparser.DEFAULTSECT:
config.add_section(section_name)
# Add items to the section
for key, value in items.items():
if isinstance(value, list):
# Handle lists
if self.split_ml_text_to_list:
# Multi-line format
value = "\n" + "\n".join(str(v) for v in value)
else:
# Python list syntax
value = str(value)
else:
value = str(value)
# parse() expands %(name)s references, so escape every %
config.set(section_name, key, value.replace("%", "%%"))
stream = StringIO()
config.write(stream)
stream.seek(0)
return stream.read()
class CompositeConfigParser(ConfigFileParser):
"""
Create a config parser composed by other ConfigFileParser instances.
The composite parser will successively try to parse the file with each parser,
until it succeeds, else raise exception with all encountered errors.
"""
def __init__(self, config_parser_types):
super().__init__()
self.parsers: list[ConfigFileParser] = [p() for p in config_parser_types]
seen_ini = False
for parser in self.parsers:
if not seen_ini and isinstance(parser, IniConfigParser):
seen_ini = True
continue
if seen_ini and isinstance(parser, TomlConfigParser):
warnings.warn(
"IniConfigParser was found before TomlConfigParser in parsers for "
"CompositeConfigParser. This might lead to a TOML file being "
"parsed as an INI file. Reorder the parsers.",
category=SyntaxWarning,
)
def __call__(self):
return self
def parse(self, stream):
errors = []
for i, p in enumerate(self.parsers):
try:
return p.parse(stream) # type: ignore[no-any-return]
except Exception as e:
if isinstance(e, ConfigFileParserMissingDependency):
# don't skip it silently, but don't take the rest of the
# chain down with it either
warnings.warn(
f"Cannot use parser {p.__class__.__name__} without "
f"optional dependency: {e}"
)
errors.append(e)
# Try to seek back to beginning for next parser
# If this is not the last parser and seek fails, we can't continue
if i < len(self.parsers) - 1:
try:
stream.seek(0)
except (AttributeError, OSError):
# Stream doesn't support seeking
raise ConfigFileParserException(
f"Error parsing config with {p.__class__.__name__}: {e}. "
f"Cannot try additional parsers because stream is not seekable."
) from e
raise ConfigFileParserException(
f"Error parsing config: {', '.join(repr(str(e)) for e in errors)}"
)
def get_syntax_description(self):
def guess_format_name(classname):
strip = (
classname.lower()
.strip("_")
.replace("parser", "")
.replace("config", "")
.replace("file", "")
)
return strip.upper() if strip else "??"
msg = "Uses multiple config parser settings (in order): \n"
for i, parser in enumerate(self.parsers):
msg += f"[{i + 1}] {guess_format_name(parser.__class__.__name__)}: {parser.get_syntax_description()} \n"
return msg
def serialize(self, items):
"""Serialize items using the first parser in the composite."""
if not self.parsers:
raise ConfigFileParserException(
"No parsers configured in CompositeConfigParser"
)
# Use the first parser to serialize
return self.parsers[0].serialize(items) # type: ignore[no-any-return]
# used while parsing args to keep track of where they came from
_COMMAND_LINE_SOURCE_KEY = "command_line"
_ENV_VAR_SOURCE_KEY = "environment_variables"
_CONFIG_FILE_SOURCE_KEY = "config_file"
_DEFAULTS_SOURCE_KEY = "defaults"
class ArgumentParser(argparse.ArgumentParser):
"""Drop-in replacement for `argparse.ArgumentParser` that adds support for
environment variables and ``.ini`` or ``.yaml-style`` config files.
"""
def __init__(self, *args, **kwargs):
r"""Supports args of the `argparse.ArgumentParser` constructor
as \*\*kwargs, as well as the following additional args.
Keyword Arguments:
add_config_file_help: Whether to add a description of config file
syntax to the help message.
add_env_var_help: Whether to add something to the help message for
args that can be set through environment variables.
auto_env_var_prefix: If set to a string instead of None, all config-
file-settable options will become also settable via environment
variables whose names are this prefix followed by the config
file key, all in upper case. (eg. setting this to ``foo_`` will
allow an arg like ``--my-arg`` to also be set via the FOO_MY_ARG
environment variable)
default_config_files: When specified, this list of config files will
be parsed in order, with the values from each config file
taking precedence over previous ones. This allows an application
to look for config files in multiple standard locations such as
the install directory, home directory, and/or current directory.
Also, shell \* syntax can be used to specify all conf files in a
directory. For example::
["/etc/conf/app_config.ini",
"/etc/conf/conf-enabled/*.ini",
"~/.my_app_config.ini",
"./app_config.txt"]
Path entries may be strings, ``os.PathLike`` objects (e.g.
``pathlib.Path``), or zero-argument callable functions that
return an open file-like object containing config file
contents. Any provided callable is invoked each time the parser opens
config files, and the returned stream is closed by the parser
after parsing. The callable must return a stream. This is useful
for sourcing config from non-filesystem locations such as in-memory
buffers, secrets managers, or HTTP responses.
ignore_unknown_config_file_keys: If true, settings that are found
in a config file but don't correspond to any defined
configargparse args will be ignored. If false, they will be
processed and appended to the commandline like other args, and
can be retrieved using parse_known_args() instead of parse_args()
config_file_open_func: function used to open a config file for reading
or writing. Needs to return a file-like object.
config_file_parser_class: configargparse.ConfigFileParser subclass
which determines the config file format. configargparse comes
with DefaultConfigFileParser and YAMLConfigFileParser.
args_for_setting_config_path: A list of one or more command line
args to be used for specifying the config file path
(eg. ["-c", "--config-file"]). Default: []
config_arg_is_required: When args_for_setting_config_path is set,
set this to True to always require users to provide a config path.
config_arg_help_message: the help message to use for the
args listed in args_for_setting_config_path.
args_for_writing_out_config_file: A list of one or more command line
args to use for specifying a config file output path. If
provided, these args cause configargparse to write out a config
file with settings based on the other provided commandline args,
environment variants and defaults, and then to exit.
(eg. ["-w", "--write-out-config-file"]). Default: []
These args can only be set on the command line. A config file
key that names one is an error, and they can't have an env_var,
since either would let whoever controls those overwrite an
arbitrary file.
write_out_config_file_arg_help_message: The help message to use for
the args in args_for_writing_out_config_file.
"""
# This is the only way to make positional args (tested in the argparse
# main test suite) and keyword arguments work across both Python 2 and
# 3. This could be refactored to not need extra local variables.
add_config_file_help = kwargs.pop("add_config_file_help", True)
add_env_var_help = kwargs.pop("add_env_var_help", True)
auto_env_var_prefix = kwargs.pop("auto_env_var_prefix", None)
default_config_files = kwargs.pop("default_config_files", [])
ignore_unknown_config_file_keys = kwargs.pop(
"ignore_unknown_config_file_keys", False
)
config_file_parser_class = kwargs.pop(
"config_file_parser_class", DefaultConfigFileParser
)
args_for_setting_config_path = kwargs.pop("args_for_setting_config_path", [])
config_arg_is_required = kwargs.pop("config_arg_is_required", False)
config_arg_help_message = kwargs.pop(
"config_arg_help_message", "config file path"
)
args_for_writing_out_config_file = kwargs.pop(
"args_for_writing_out_config_file", []
)
write_out_config_file_arg_help_message = kwargs.pop(
"write_out_config_file_arg_help_message",
"takes the current "
"command line args and writes them out to a config file at the "
"given path, then exits",
)
config_file_open_func = kwargs.pop("config_file_open_func", open)
# Validate args before proceeding
for name, value in [
("default_config_files", default_config_files),
("args_for_setting_config_path", args_for_setting_config_path),
("args_for_writing_out_config_file", args_for_writing_out_config_file),
]:
if not isinstance(value, (list, tuple)):
hint = " (e.g. ['%s'])" % value if isinstance(value, str) else ""
raise TypeError("%s must be a list%s. Got: %r" % (name, hint, value))
for i, entry in enumerate(default_config_files):
if not (isinstance(entry, (str, bytes, os.PathLike)) or callable(entry)):
raise TypeError(
"default_config_files[%d] must be a string, bytes, or "
"os.PathLike path, or a callable that returns an open "
"file-like object. Got: %r" % (i, entry)
)
if not callable(config_file_open_func):
raise TypeError(
"config_file_open_func must be callable. Got: %r"
% (config_file_open_func,)
)
self._config_file_open_func = config_file_open_func
self._add_config_file_help = add_config_file_help
self._add_env_var_help = add_env_var_help
self._auto_env_var_prefix = auto_env_var_prefix
if "formatter_class" in kwargs:
fc = kwargs["formatter_class"]
if isinstance(fc, type) and not issubclass(fc, argparse.HelpFormatter):
msg = (
"formatter_class must be a subclass of "
"argparse.HelpFormatter. Got: %r." % (fc,)
)
if issubclass(fc, ConfigFileParser):
msg += " Perhaps you meant to use config_file_parser_class?"
raise TypeError(msg)
argparse.ArgumentParser.__init__(self, *args, **kwargs)
# parse the additional args
if config_file_parser_class is None:
self._config_file_parser = DefaultConfigFileParser()
elif isinstance(config_file_parser_class, ConfigFileParser):
self._config_file_parser = config_file_parser_class
elif isinstance(config_file_parser_class, type) and issubclass(
config_file_parser_class, ConfigFileParser
):
self._config_file_parser = config_file_parser_class()
else:
raise TypeError(
"config_file_parser_class must be a subclass of "
"ConfigFileParser (such as DefaultConfigFileParser, "
"YAMLConfigFileParser, etc.). "
"Got: %r. Perhaps you meant to use formatter_class?"
% (config_file_parser_class,)
)
self._default_config_files = default_config_files
self._ignore_unknown_config_file_keys = ignore_unknown_config_file_keys
if args_for_setting_config_path:
self.add_argument(
*args_for_setting_config_path,
dest="config_file",
required=config_arg_is_required,
help=config_arg_help_message,
is_config_file_arg=True,
)
if args_for_writing_out_config_file:
self.add_argument(
*args_for_writing_out_config_file,
dest="write_out_config_file_to_this_path",
metavar="CONFIG_OUTPUT_PATH",
help=write_out_config_file_arg_help_message,
is_write_out_config_file_arg=True,
)
# Workaround for Python < 3.9: exit_on_error parameter was added in 3.9
# This can be removed when minimum Python version is raised to 3.9+
if sys.version_info < (3, 9):
self.exit_on_error = True
def _find_insertion_index(self, args):
"""Find the right index to insert config/env var args into the command line.
Inserts before the ``--`` separator if present, before a subparser
command so the parent parser sees injected args first, before the
first optional arg, or at position 0 when a REMAINDER positional
exists. Falls back to appending.
"""
if "--" in args:
return args.index("--")
subcmd_index = self._find_subcommand_index(args)
if subcmd_index is not None:
return subcmd_index
first_opt = None
for i, arg in enumerate(args):
if arg.startswith(tuple(self.prefix_chars)):
first_opt = i
break
if first_opt is not None:
return first_opt
# No optional args on command line
if any(
a.is_positional_arg and a.nargs == argparse.REMAINDER for a in self._actions
):
return 0
return len(args)
def _find_subcommand_index(self, args):
"""Find where the subcommand is on the command line, if there is one.
Args:
args: the command line args.
Returns:
int or None: the index of the first arg naming a subcommand
"""
for action in self._actions:
if isinstance(action, argparse._SubParsersAction) and action.choices:
for i, arg_string in enumerate(args):
if arg_string in action.choices:
return i
return None
return None
def _option_strings_that_override(self, action):
"""Find the option strings that, when already on the command line, mean
an env var or config file value for the given action should be dropped.
These are the action's own option strings plus those of every other
action in the same mutually exclusive group, mirroring the conflicts
argparse checks for. Without the latter, a config file value for one
member of a group would clash with a different member given on the
command line instead of being overridden by it (see issue #164).
Args:
action: the argparse.Action to find overriding option strings for.
Returns:
list[str]: the option strings
"""
option_strings = list(action.option_strings)
for group in self._mutually_exclusive_groups:
if action in group._group_actions:
for other_action in group._group_actions:
if other_action is not action:
option_strings += other_action.option_strings
return option_strings
def parse_args(
self, args=None, namespace=None, config_file_contents=None, env_vars=os.environ
):
"""Supports all the same args as the `argparse.ArgumentParser.parse_args()`,
as well as the following additional args.
Arguments:
args: a list of args as in argparse, or a string (eg. "-x -y bla")
config_file_contents: String. Used for testing.
env_vars: Dictionary. Used for testing.
Returns:
argparse.Namespace: namespace
"""
args, argv = self.parse_known_args(
args=args,
namespace=namespace,
config_file_contents=config_file_contents,
env_vars=env_vars,
ignore_help_args=False,
)
if argv:
msg = "unrecognized arguments: %s" % " ".join(argv)
if self.exit_on_error:
self.error(msg)
else:
raise ArgumentError(None, msg)
return args
def parse_known_args(
self,
args=None,
namespace=None,
config_file_contents=None,
env_vars=os.environ,
ignore_help_args=False,
):
"""Supports all the same args as the `argparse.ArgumentParser.parse_args()`,
as well as the following additional args.
Arguments:
args: a list of args as in argparse, or a string (eg. "-x -y bla")
config_file_contents (str). Used for testing.
env_vars (dict). Used for testing.
ignore_help_args (bool): This flag determines behavior when user specifies ``--help`` or ``-h``. If False,
it will have the default behavior - printing help and exiting. If True, it won't do either.
Returns:
tuple[argparse.Namespace, list[str]]: tuple namescpace, unknown_args
"""
if args is None:
args = sys.argv[1:]
elif isinstance(args, str):
args = args.split()
else:
args = list(args)
for a in self._actions:
a.is_positional_arg = not a.option_strings
if ignore_help_args:
args = [arg for arg in args if arg not in ("-h", "--help")]
# maps a string describing the source (eg. env var) to a settings dict
# to keep track of where values came from (used by print_values()).
# The settings dicts for env vars and config files will then map
# the config key to an (argparse Action obj, string value) 2-tuple.
self._source_to_settings = OrderedDict()
if args:
a_v_pair = (None, list(args)) # copy args list to isolate changes
self._source_to_settings[_COMMAND_LINE_SOURCE_KEY] = {"": a_v_pair}
# handle auto_env_var_prefix __init__ arg by setting a.env_var as needed
if self._auto_env_var_prefix is not None:
for a in self._actions:
config_file_keys = self.get_possible_config_keys(a)
if config_file_keys and not (
a.env_var
or a.is_positional_arg
or a.is_config_file_arg
or a.is_write_out_config_file_arg
or isinstance(a, argparse._VersionAction)
or isinstance(a, argparse._HelpAction)
):
stripped_config_file_key = config_file_keys[0].strip(
self.prefix_chars
)
a.env_var = (
(self._auto_env_var_prefix + stripped_config_file_key)
.replace("-", "_")
.upper()
)
# add env var settings to the commandline that aren't there already
env_var_args = []
env_var_settings = OrderedDict()
env_var_flag_actions = set()
# A flag set to false (eg. FOO=false for a store_true arg) adds no args
# to the command line, so already_on_command_line() can't tell it was
# set, yet it should still keep lower-priority sources from setting
# that flag (see issue #105). So remember the flags each source sets.
# Only flags: an append arg set to an empty list also adds no args, but
# it has never overridden lower-priority sources, and making it do so
# would leave it None rather than an empty list.
flag_actions_set_by_higher_priority_sources = set()
actions_with_env_var_values = [
a
for a in self._actions
if not a.is_positional_arg
and a.env_var
and a.env_var in env_vars
and not already_on_command_line(
args, self._option_strings_that_override(a), self.prefix_chars
)
]
for action in actions_with_env_var_values:
key = action.env_var
value = env_vars[key]
# Skip empty string env vars for args with nargs to match YAML behavior
# where empty values are treated as None/not present (see issue #296)
if value == "" and action.nargs:
continue
# Make list-string into list.
if action.nargs or isinstance(action, argparse._AppendAction):
if value.startswith("[") and value.endswith("]"):
# handle special case of k=[1,2,3] or other json-like syntax
try:
value = json.loads(value)
except Exception:
# for backward compatibility with legacy format (eg. where config value is [a, b, c] instead of proper json ["a", "b", "c"]
value = [elem.strip() for elem in value[1:-1].split(",")]
env_var_args += self.convert_item_to_command_line_arg(action, key, value)
env_var_settings[key] = (action, env_vars[key])
if isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE):
env_var_flag_actions.add(action)
idx = self._find_insertion_index(args)
if self._reject_write_out_config_file_args(
env_var_args, "in an environment variable", self._reachable_parsers()
):
args = args[:idx] + env_var_args + args[idx:]
flag_actions_set_by_higher_priority_sources.update(env_var_flag_actions)
if env_var_settings:
self._source_to_settings[_ENV_VAR_SOURCE_KEY] = env_var_settings
# before parsing any config files, check if -h was specified.
supports_help_arg = any(
a for a in self._actions if isinstance(a, argparse._HelpAction)
)
skip_config_file_parsing = supports_help_arg and (
"-h" in args or "--help" in args
)
# prepare for reading config file(s)
known_config_keys = {
config_key: action
for action in self._actions
for config_key in self.get_possible_config_keys(action)
}
# open the config file(s). config_streams is a list of (stream, source_label) tuples.
config_streams = []
if config_file_contents is not None:
stream = StringIO(config_file_contents)
stream.name = "method arg"
config_streams = [(stream, "method arg")]
elif not skip_config_file_parsing:
config_streams = self._open_config_files(args)
# parse each config file
try:
for stream, source_label in reversed(config_streams):
try:
config_items = self._config_file_parser.parse(stream)
except ConfigFileParserException as e:
self.error(str(e))
# add each config item to the commandline unless it's there already
config_args = []
config_file_flag_actions = set()
for key, value in config_items.items():
if key in known_config_keys:
action = known_config_keys[key]
discard_this_key = (
action in flag_actions_set_by_higher_priority_sources
or already_on_command_line(
args,
self._option_strings_that_override(action),
self.prefix_chars,
)
)
else:
action = None
discard_this_key = (
self._ignore_unknown_config_file_keys
or already_on_command_line(
args,
[
self.get_command_line_key_for_unknown_config_file_setting(
key
)
],
self.prefix_chars,
)
)
# Skip empty string values for args with nargs to match YAML behavior
# where empty values are treated as None/not present (see issue #296)
if value == "" and action and action.nargs:
continue
if not discard_this_key:
config_args += self.convert_item_to_command_line_arg(
action, key, value
)
if isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE):
config_file_flag_actions.add(action)
source_key = "%s|%s" % (
_CONFIG_FILE_SOURCE_KEY,
source_label,
)
if source_key not in self._source_to_settings:
self._source_to_settings[source_key] = OrderedDict()
self._source_to_settings[source_key][key] = (action, value)
idx = self._find_insertion_index(args)
if self._reject_write_out_config_file_args(
config_args,
"in a config file (%s)" % source_label,
self._reachable_parsers(),
):
args = args[:idx] + config_args + args[idx:]
# Update between sources, not between entries in one file.
flag_actions_set_by_higher_priority_sources.update(
config_file_flag_actions
)
finally:
# Close every stream exactly once, regardless of whether parsing
# succeeded or aborted partway through (e.g. a custom parser
# raised a non-ConfigFileParserException).
for stream, _ in config_streams:
try:
if hasattr(stream, "close"):
stream.close()
except Exception:
pass
# save default settings for use by print_values()
default_settings = OrderedDict()
for action in self._actions:
cares_about_default_value = (
not action.is_positional_arg or action.nargs in [OPTIONAL, ZERO_OR_MORE]
)
if (
already_on_command_line(args, action.option_strings, self.prefix_chars)
or not cares_about_default_value
or action.default is None
or action.default == SUPPRESS
or isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE)
):
continue
else:
if action.option_strings:
key = action.option_strings[-1]
else:
key = action.dest
default_settings[key] = (action, str(action.default))
if default_settings:
self._source_to_settings[_DEFAULTS_SOURCE_KEY] = default_settings
# parse all args (including commandline, config file, and env var)
self._write_out_config_file_paths = OrderedDict()
namespace, unknown_args = argparse.ArgumentParser.parse_known_args(
self, args=args, namespace=namespace
)
output_file_paths = [
path
for path in self._write_out_config_file_paths.values()
if path is not None
]
# handle any args that have is_write_out_config_file_arg set to true.
# Each one recorded its own path as it was parsed, which is the only
# place that path can have come from, and the args built from config
# files and env vars were kept from setting one at all above.
self.write_config_file(namespace, output_file_paths, exit_after=True)
return namespace, unknown_args
def get_source_to_settings_dict(self):
"""
If called after `parse_args()` or `parse_known_args()`, returns a dict that contains up to 4 keys corresponding
to where a given option's value is coming from:
- "command_line"
- "environment_variables"
- "config_file"
- "defaults"
Each such key, will be mapped to another dictionary containing the options set via that method. Here the key
will be the option name, and the value will be a 2-tuple of the form (`argparse.Action` obj, `str` value).
Returns:
dict[str, dict[str, tuple[argparse.Action, str]]]: source to settings dict
"""
# _source_to_settings is set in parse_know_args().
return self._source_to_settings # type: ignore[attribute-error]
def _reject_write_out_config_file_args(
self, synthesized_args, source_description, parsers
):
"""Reject synthesized command line args that set a write-out-config-file arg.
Config file entries and environment variables are turned into command
line args and then parsed like any others, so either one's key or its
value can end up naming an arg. A write-out-config-file arg overwrites
the path it is given and then exits the program, so only the real
command line may set one: otherwise whoever controls a config file the
program reads could destroy an arbitrary file without the user passing
any args at all. (This is also why get_possible_config_keys() keeps
these args out of the keys a config file can set.)
These args are checked against every parser reachable from this one,
not just the one that looks like it will parse them. Which subcommand
runs can't be told from the args: an option's value reads exactly like
a subcommand name, and the synthesized args can name a subcommand
themselves. So a config file may not name a write-out arg anywhere in
the parser tree, which costs an error on a key named after one on a
subcommand that wasn't going to run.
Args:
synthesized_args: command line args built from a config file or from
environment variables, before they are added to the real ones.
source_description: where they came from, for the error message.
parsers: the parsers that could end up parsing them.
Returns:
bool: whether the args may be used. error() is meant to stop the
program, but a program can override exit(), so this says so rather
than counting on the call not returning.
"""
if not self._write_out_config_file_args(parsers):
return True
# any of these parsers could be the one to expand an arg that names a
# file of args, and each has its own idea of which chars start one
fromfile_prefix_chars = "".join(
parser.fromfile_prefix_chars or ""
for parser in parsers
if self._write_out_config_file_args(_subparsers_of(parser))
)
for arg_string in synthesized_args:
if self._names_a_write_out_config_file_arg(arg_string, parsers):
self.error(
"%s can only be set on the command line, not %s"
% (arg_string.split("=", 1)[0], source_description)
)
return False
if arg_string and arg_string[0] in fromfile_prefix_chars:
# argparse replaces this with the args read from that file, and
# it does so after this check, so the file's contents would go
# unchecked and could name any arg at all
self.error(
"%s can't be used %s, since it would read command line args "
"from a file" % (arg_string, source_description)
)
return False
return True
def _names_a_write_out_config_file_arg(self, arg_string, parsers):
"""Check whether a command line arg would set a write-out-config-file arg.
Args:
arg_string: a single command line arg.
parsers: the parsers that could end up parsing it.
Returns:
bool: whether it names a write-out-config-file arg
"""
return any(
# a parser that isn't one of ours has no matcher of its own, and
# this one's is close enough to decide against
getattr(parser, "_could_set_option", self._could_set_option)(
arg_string, option_string
)
for parser, action in self._write_out_config_file_args(parsers)
for option_string in action.option_strings
)
def _reachable_parsers(self):
"""Find this parser and every subparser these args could be handed to.
A subparser is given the args this parser has put together and treats
them as its own command line, and argparse parses it into this parser's
namespace, so both what a subparser accepts and what it stores matter
here. Subparsers that aren't ConfigArgParse parsers are walked through
as well, since one of them can hold a subparser that is.
Returns:
list[argparse.ArgumentParser]: this parser and its subparsers
"""
return _subparsers_of(self)
def _write_out_config_file_args(self, parsers):
"""Find the write-out-config-file args the given parsers define.
Args:
parsers: the parsers to look in.
Returns:
list: each such arg as an ``(argparse.ArgumentParser,
argparse.Action)`` pair, since it's the parser an arg belongs to
that decides which command line args can set it.
"""
return [
(parser, action)
for parser in parsers
for action in parser._actions
if getattr(action, "is_write_out_config_file_arg", False)
]
def _could_set_option(self, arg_string, option_string):
"""Check whether a command line arg could set the given option.
This covers every form argparse accepts: the option on its own, with its
value attached after an ``=`` (or, for a short option, straight after
it), bundled with other short options, and abbreviated. Where argparse
would need to look at the rest of the command line to decide, this says
yes, since it is used to reject args that must not reach an option at
all, and being wrong in that direction only costs an error message.
Args:
arg_string: a single command line arg.
option_string: an option string of the option to look for.
Returns:
bool: whether the arg could set the option
"""
if arg_string == option_string:
return True
if arg_string == "--":
# argparse's end-of-options separator, which it matches literally
# rather than through prefix_chars, and never treats as an option
return False
if len(arg_string) < 2 or arg_string[0] not in self.prefix_chars:
return False
# argparse looks for an option matching the part before any '=' first,
# whatever the option's prefix. Failing that, a long option is looked up
# by that same part, while a short one keeps whatever follows it, since
# a short option's value can be attached straight to it.
is_long_option = arg_string[1] in self.prefix_chars
bare_key = arg_string.split("=", 1)[0]
key = bare_key if is_long_option else arg_string
if bare_key == option_string or key == option_string:
return True
matched_action = self._option_string_actions.get(
bare_key, self._option_string_actions.get(key)
)
if matched_action is not None and (
is_long_option or getattr(matched_action, "nargs", None) != 0
):
# argparse resolves an exact match straight to that option, so an
# arg naming a different one can never reach this one. The exception
# is a single prefix char naming an option that takes no value:
# before Python 3.11 argparse goes on to read the rest of that arg
# as more short options, so keep looking.
return False
if is_long_option:
# only an unambiguous abbreviation can reach it from here
return self.allow_abbrev and option_string.startswith(key)
if option_string.startswith(bare_key):
# argparse looks a single-prefix-char arg up by the part before any
# '=' and takes any option starting with it, so even a lone prefix
# char reaches an option when it is the only candidate. Before
# Python 3.13 it does this whatever allow_abbrev says.
return True
if len(option_string) != 2:
# an option with a single prefix char but a longer name is only
# reachable whole or abbreviated, which the check above covers
return False
# a short option can also follow other short options that take no value
# of their own, with its own value attached after it. When the part
# before an '=' is itself a flag that takes no value, argparse before
# 3.11.9 and 3.12.3 starts reading short options after the '=' instead.
bundled = (
arg_string.split("=", 1)[1]
if matched_action is not None and "=" in arg_string
else arg_string[1:]
)
index = bundled.find(option_string[1])
if index == -1:
return False
return all(
getattr(self._option_string_actions.get(arg_string[0] + c), "nargs", None)
== 0
for c in bundled[:index]
if c != "="
)
def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False):
"""Write the given settings to output files.
Args:
parsed_namespace: namespace object created within parse_known_args()
output_file_paths: any number of file paths to write the config to
exit_after: whether to exit the program after writing the config files
"""
if output_file_paths:
# generate the config file contents first. Opening an output file
# truncates it, so nothing is opened until the contents that will
# replace it exist. Each file is then opened exactly once, which
# also avoids the gap between checking a path and writing to it.
config_items = self.get_items_for_config_file_output(
self._source_to_settings, parsed_namespace
)
file_contents = self._config_file_parser.serialize(config_items)
for output_file_path in output_file_paths:
try:
with self._config_file_open_func(
output_file_path, "w"
) as output_file:
output_file.write(file_contents)
except IOError as e:
raise ValueError(
"Couldn't open {} for writing: {}".format(output_file_path, e)
)
print("Wrote config file to " + ", ".join(output_file_paths))
if exit_after:
self.exit(0)
def get_command_line_key_for_unknown_config_file_setting(self, key):
"""Compute a commandline arg key to be used for a config file setting
that doesn't correspond to any defined configargparse arg (and so
doesn't have a user-specified commandline arg key).
Args:
key: The config file key that was being set.
Returns:
str: command line key
"""
key_without_prefix_chars = key.strip(self.prefix_chars)
command_line_key = self.prefix_chars[0] * 2 + key_without_prefix_chars
return command_line_key
def get_items_for_config_file_output(self, source_to_settings, parsed_namespace):
"""Converts the given settings back to a dictionary that can be passed
to ConfigFormatParser.serialize(..).
Args:
source_to_settings: the dictionary described in parse_known_args()
parsed_namespace: namespace object created within parse_known_args()
Returns:
OrderedDict: where keys are strings and values are either strings
or lists
"""
config_file_items = OrderedDict()
for source, settings in source_to_settings.items():
if source == _COMMAND_LINE_SOURCE_KEY:
_, existing_command_line_args = settings[""]
for action in self._actions:
config_file_keys = self.get_possible_config_keys(action)
if (
config_file_keys
and not action.is_positional_arg
and already_on_command_line(
existing_command_line_args,
action.option_strings,
self.prefix_chars,
)
):
value = getattr(parsed_namespace, action.dest, None)
if value is not None:
config_file_items[config_file_keys[0]] = (
_convert_parsed_value_to_config_file_value(
action, value
)
)
elif source == _ENV_VAR_SOURCE_KEY:
for key, (action, value) in settings.items():
config_file_keys = self.get_possible_config_keys(action)
if config_file_keys:
value = getattr(parsed_namespace, action.dest, None)
if value is not None:
config_file_items[config_file_keys[0]] = (
_convert_parsed_value_to_config_file_value(
action, value
)
)
elif source.startswith(_CONFIG_FILE_SOURCE_KEY):
for key, (action, value) in settings.items():
config_file_items[key] = value
elif source == _DEFAULTS_SOURCE_KEY:
for key, (action, value) in settings.items():
config_file_keys = self.get_possible_config_keys(action)
if config_file_keys:
value = getattr(parsed_namespace, action.dest, None)
if value is not None:
config_file_items[config_file_keys[0]] = value
return config_file_items
def convert_item_to_command_line_arg(self, action, key, value):
"""Converts a config file or env var key + value to a list of
commandline args to append to the commandline.
Args:
action: The argparse Action object for this setting, or None if this
config file setting doesn't correspond to any defined
configargparse arg.
key: string (config file key or env var name)
value: parsed value of type string or list
Returns:
list[str]: args
"""
args = []
if action is None:
command_line_key = (
self.get_command_line_key_for_unknown_config_file_setting(key)
)
else:
if not is_boolean_optional_action(action):
command_line_key = action.option_strings[-1]
# handle boolean value
if action is not None and isinstance(
action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE
):
assert isinstance(
value, str
), "config parser should convert anything that is not a list to string."
if value.lower() in ("true", "yes", "on", "1"):
if not is_boolean_optional_action(action):
args.append(command_line_key)
else:
# --foo
args.append(action.option_strings[0])
elif value.lower() in ("false", "no", "off", "0"):
# don't append when set to "false" / "no"
if not is_boolean_optional_action(action):
pass
else:
# --no-foo
args.append(action.option_strings[1])
elif isinstance(action, argparse._CountAction):
# For count actions, repeat the flag the number of times specified
args += [action.option_strings[0]] * int(value)
else:
self.error(
"Unexpected value for %s: '%s'. Expecting 'true', "
"'false', 'yes', 'no', 'on', 'off', '1' or '0'" % (key, value)
)
elif isinstance(value, list):
# Only nargs is relevant here: any action, including a custom
# argparse.Action subclass, consumes several values when nargs
# allows it. Testing the action class as well would be redundant,
# since actions that cannot consume a list have an nargs that
# fails the test below anyway: 0 or None for store_const, count
# and friends, 'A...' for subparsers, '...' for REMAINDER.
accepts_list_and_has_nargs = action is not None and (
action.nargs in ("+", "*")
or (isinstance(action.nargs, int) and action.nargs > 1)
)
if action is None or isinstance(action, argparse._AppendAction):
for list_elem in value:
if accepts_list_and_has_nargs and isinstance(list_elem, list):
args.append(command_line_key)
for sub_elem in list_elem:
args.append(str(sub_elem))
else:
args.append("%s=%s" % (command_line_key, str(list_elem)))
elif accepts_list_and_has_nargs:
args.append(command_line_key)
for list_elem in value:
args.append(str(list_elem))
else:
self.error(
(
"%s can't be set to a list '%s' unless its action type is changed "
"to 'append' or nargs is set to '*', '+', or > 1"
)
% (key, value)
)
# argparse ends option parsing at the first bare '--', so one taken
# from a list would turn the user's own command line options after
# it into positional args, and hide them from the checks that let
# them override config file and env var values
if "--" in args:
self.error(
"%s can't have '--' as a list element, since it would end "
"option parsing" % key
)
return []
elif isinstance(value, str):
args.append("%s=%s" % (command_line_key, value))
else:
raise ValueError(
"Unexpected value type {} for value: {}".format(type(value), value)
)
return args
def get_possible_config_keys(self, action):
"""This method decides which actions can be set in a config file and
what their keys will be. It returns a list of 0 or more config keys that
can be used to set the given action's value in a config file.
Returns:
list[str]: keys
"""
keys = []
# Do not write out the config options for writing out a config file
if getattr(action, "is_write_out_config_file_arg", None):
return keys
for arg in action.option_strings:
if any(arg.startswith(2 * c) for c in self.prefix_chars):
keys += [arg[2:], arg] # eg. for '--bla' return ['bla', '--bla']
return keys
def _open_config_files(self, command_line_args):
"""Tries to parse config file path(s) from within command_line_args.
Returns a list of opened config files, including files specified on the
commandline as well as any default_config_files specified in the
constructor that are present on disk.
Args:
command_line_args: List of all args
Returns:
list[tuple[io.IOBase, str]]: list of ``(stream, source_label)``
pairs. The ``source_label`` is unique per entry (file path for
path entries; ``"[]"`` for callable entries),
so different entries cannot collapse into a single source key in
``format_values()``.
"""
# open any default config files
config_files = []
try:
for i, entry in enumerate(self._default_config_files):
if isinstance(entry, (str, os.PathLike)):
# Path entries (str or PathLike). Checked before callable so
# objects implementing both __fspath__ and __call__ are
# treated as paths, matching the documented behavior.
for f in glob.glob(os.path.expanduser(os.fspath(entry))):
config_files.append((self._config_file_open_func(f), f))
else:
# Callable entry (validation in __init__ guarantees this).
entry_label = getattr(entry, "__name__", repr(entry))
try:
stream = entry()
except Exception as e:
raise ConfigFileParserException(
"default_config_files entry %r raised while being "
"called: %s" % (entry_label, e)
) from e
if stream is None:
raise TypeError(
"default_config_files entry %r returned None; "
"must return an open file-like object." % (entry_label,)
)
# Use a source label that always includes the entry index
# so two callables returning streams with the same .name
# (or even the same library-generated name from a previous
# iteration) cannot collide into one _source_to_settings
# entry. The label also doubles as stream.name when the
# stream lacks one, for readable parser error messages.
display_name = (
getattr(stream, "name", None)
if hasattr(stream, "name")
else None
)
source_label = "%s[%d]" % (display_name or entry_label, i)
# Append before attempting .name so the outer cleanup
# closes the stream if the assignment below raises.
config_files.append((stream, source_label))
if not hasattr(stream, "name"):
try:
stream.name = source_label
except Exception as e:
raise ConfigFileParserException(
"default_config_files entry %r returned a "
"stream whose .name attribute could not be "
"set: %s" % (entry_label, e)
) from e
# list actions with is_config_file_arg=True. Its possible there is
# more than one such arg.
user_config_file_arg_actions = [
a for a in self._actions if getattr(a, "is_config_file_arg", False)
]
if not user_config_file_arg_actions:
return config_files
for action in user_config_file_arg_actions:
# try to parse out the config file path by using a clean new
# ArgumentParser that only knows this one arg/action.
arg_parser = argparse.ArgumentParser(
prefix_chars=self.prefix_chars, add_help=False
)
arg_parser._add_action(action)
# make parser not exit on error by replacing its error method.
# Otherwise it sys.exits(..) if, for example, config file
# is_required=True and user doesn't provide it.
def error_method(self, message):
pass
arg_parser.error = types.MethodType(error_method, arg_parser)
# check whether the user provided a value
namespace, _ = arg_parser.parse_known_args(args=command_line_args)
user_config_file = getattr(namespace, action.dest, None)
if not user_config_file:
continue
# open user-provided config file
user_config_file = os.path.expanduser(user_config_file)
try:
stream = self._config_file_open_func(user_config_file)
except Exception as e:
self.error(
"Unable to open config file: %s. Error: %s"
% (user_config_file, str(e))
)
config_files.append((stream, user_config_file))
return config_files
except BaseException:
# If anything in the body above raises (callable failure, .name
# assignment failure, glob/open failure, an inner argparse type=
# callback raising during user-config-file parsing, self.error()
# exiting, etc.), close every stream we opened so we don't leak
# file handles. close() is idempotent for standard streams, so it
# is safe to call on streams already closed by a nested handler.
for cf, _ in config_files:
try:
if hasattr(cf, "close"):
cf.close()
except Exception:
pass
raise
def format_values(self):
"""Returns a string with all args and settings and where they came from
(eg. commandline, config file, environment variable or default)
Returns:
str: source to settings string
"""
source_key_to_display_value_map = {
_COMMAND_LINE_SOURCE_KEY: "Command Line Args: ",
_ENV_VAR_SOURCE_KEY: "Environment Variables:\n",
_CONFIG_FILE_SOURCE_KEY: "Config File (%s):\n",
_DEFAULTS_SOURCE_KEY: "Defaults:\n",
}
r = StringIO()
for (
source,
settings,
) in self._source_to_settings.items(): # type: ignore[argument-error]
source = source.split("|", 1)
source = source_key_to_display_value_map[source[0]] % tuple(source[1:])
r.write(source)
for key, (action, value) in settings.items():
if key:
r.write(" {:<19}{}\n".format(key + ":", value))
else:
if isinstance(value, str):
r.write(" %s\n" % value)
elif isinstance(value, list):
r.write(" %s\n" % " ".join(value))
return r.getvalue()
def print_values(self, file=sys.stdout):
"""Prints the format_values() string (to sys.stdout or another file)."""
file.write(self.format_values())
def format_help(self):
msg = ""
added_config_file_help = False
added_env_var_help = False
if self._add_config_file_help:
default_config_files = self._default_config_files
cc = 2 * self.prefix_chars[0] # eg. --
config_settable_args = [
(arg, a)
for a in self._actions
for arg in a.option_strings
if self.get_possible_config_keys(a)
and not (
a.dest == "help"
or a.is_config_file_arg
or a.is_write_out_config_file_arg
)
]
config_path_actions = [
a for a in self._actions if getattr(a, "is_config_file_arg", False)
]
if config_settable_args and (default_config_files or config_path_actions):
self._add_config_file_help = False # prevent duplication
added_config_file_help = True
msg += (
"Args that start with '%s' can also be set in a config file"
) % cc
config_arg_string = " or ".join(
a.option_strings[0] for a in config_path_actions if a.option_strings
)
if config_arg_string:
config_arg_string = "specified via " + config_arg_string
if default_config_files or config_arg_string:
# Mirror _open_config_files: path entries (str/PathLike)
# are checked before callable, so an object that is both
# PathLike and callable is rendered as a path here too.
# os.fsdecode() handles bytes-returning __fspath__ (PEP
# 519 allows it); the try/except handles malformed
# PathLike whose __fspath__ returns the wrong type.
def _describe_default_config_file_entry(e):
if isinstance(e, (str, os.PathLike)):
try:
return os.fsdecode(os.fspath(e))
except (TypeError, ValueError):
return repr(e)
return getattr(e, "__name__", "")
described_files = tuple(
_describe_default_config_file_entry(e)
for e in default_config_files
)
msg += " (%s)." % " or ".join(
described_files + tuple(filter(None, [config_arg_string]))
)
msg += " " + self._config_file_parser.get_syntax_description()
if self._add_env_var_help:
env_var_actions = [
(a.env_var, a) for a in self._actions if getattr(a, "env_var", None)
]
for env_var, a in env_var_actions:
if a.help == SUPPRESS:
continue
env_var_help_string = " [env var: %s]" % env_var
if not a.help:
a.help = ""
if env_var_help_string not in a.help:
a.help += env_var_help_string
added_env_var_help = True
self._add_env_var_help = False # prevent duplication
if added_env_var_help or added_config_file_help:
value_sources = ["defaults"]
if added_config_file_help:
value_sources = ["config file values"] + value_sources
if added_env_var_help:
value_sources = ["environment variables"] + value_sources
msg += " In general, command-line values override %s." % (
" which override ".join(value_sources)
)
text_width = max(self._get_formatter()._width, 11)
msg = textwrap.fill(msg, text_width)
return argparse.ArgumentParser.format_help(self) + (
"\n{}\n".format(msg) if msg != "" else ""
)
def add_argument(self, *args, **kwargs):
"""
This method supports the same args as ArgumentParser.add_argument(..)
as well as the additional args below.
Keyword Arguments:
env_var: If set, the value of this environment variable will override
any config file or default values for this arg (but can itself
be overridden on the commandline). Also, if auto_env_var_prefix is
set in the constructor, this env var name will be used instead of
the automatic name.
is_config_file_arg: If True, this arg is treated as a config file path
This provides an alternative way to specify config files in place of
the ArgumentParser(fromfile_prefix_chars=..) mechanism.
Default: False
is_write_out_config_file_arg: If True, this arg will be treated as a
config file path, and, when it is specified on the command line,
will cause configargparse to write all current commandline args to
this file as config options and then exit. It can only be set on the
command line: a config file key that names it is an error, and it
can't be combined with env_var, nor be a positional arg, since a
config file value would be indistinguishable from a path the user
typed and could overwrite an arbitrary file.
Default: False
Returns:
argparse.Action: the new argparse action
"""
env_var = kwargs.pop("env_var", None)
is_config_file_arg = kwargs.pop("is_config_file_arg", None) or kwargs.pop(
"is_config_file", None
) # for backward compat.
is_write_out_config_file_arg = kwargs.pop("is_write_out_config_file_arg", None)
action = self.original_add_argument_method(*args, **kwargs)
if is_write_out_config_file_arg and isinstance(action, argparse._StoreAction):
# this arg has to record the path it is given as it is parsed, rather
# than leave it to be read back out of the namespace later. Whatever
# store action the program asked for keeps doing its own work.
action.__class__ = type(
type(action).__name__,
(_WriteOutConfigFileActionMixin, type(action)),
{},
)
action.is_positional_arg = not action.option_strings
action.env_var = env_var
action.is_config_file_arg = is_config_file_arg
action.is_write_out_config_file_arg = is_write_out_config_file_arg
if action.is_positional_arg and env_var:
raise ValueError("env_var can't be set for a positional arg.")
if action.is_config_file_arg and not isinstance(action, argparse._StoreAction):
raise ValueError("arg with is_config_file_arg=True must have action='store'")
if action.is_write_out_config_file_arg:
error_prefix = "arg with is_write_out_config_file_arg=True "
if not isinstance(action, _WriteOutConfigFileActionMixin):
raise ValueError(error_prefix + "must have action='store'")
if is_config_file_arg:
raise ValueError(error_prefix + "can't also have is_config_file_arg=True")
if env_var:
# writing out a config file overwrites the given path and then
# exits, so an env var that sets one could destroy an arbitrary file
raise ValueError(error_prefix + "can't also have env_var set")
if action.is_positional_arg:
# a config file value becomes a plain command line arg, and a
# positional would take one of those just as readily as one the user
# typed, leaving no way to keep a config file from choosing the path
# that gets overwritten
raise ValueError(error_prefix + "can't be a positional arg")
return action
def _subparsers_of(parser, seen=None):
"""Find a parser and every subparser reachable from it.
Args:
parser: the parser to start from.
seen: ids of the parsers already visited, so that a subparser leading
back to one of its own ancestors doesn't loop forever.
Returns:
list[argparse.ArgumentParser]: the parser and its subparsers
"""
if seen is None:
seen = set()
if id(parser) in seen:
return []
seen.add(id(parser))
parsers = [parser]
for action in getattr(parser, "_actions", []):
if _dispatches_to_subparsers(action):
for subparser in action.choices.values():
if isinstance(subparser, argparse.ArgumentParser):
parsers += _subparsers_of(subparser, seen)
return parsers
def _dispatches_to_subparsers(action):
"""Check whether an action hands the rest of the command line to a subparser.
Nearly always this is an ``argparse._SubParsersAction``, but a program can
register a class of its own for the job, so recognize the shape too: a
mapping of subcommand names to parsers, taking the rest of the args.
Args:
action: the action to check.
Returns:
bool: whether it dispatches to subparsers
"""
if isinstance(action, argparse._SubParsersAction):
return True
return getattr(action, "nargs", None) in (
argparse.PARSER,
argparse.REMAINDER,
) and isinstance(getattr(action, "choices", None), dict)
def _convert_parsed_value_to_config_file_value(action, value):
"""Convert a parsed arg value to the value a config file should hold for it.
For a flag (``store_true``, ``store_false`` or ``store_const``), the config
file value says whether to invoke the flag, not what it stores, so it is
``"true"`` exactly when the parsed value is the one the flag stores. Other
booleans are written in lowercase too, so values from the command line and
from environment variables are written the same way.
Args:
action: the action the value was parsed for.
value: the value the parser stored for the action.
Returns:
object: ``"true"`` or ``"false"`` for flags and booleans, otherwise the
value unchanged.
"""
if isinstance(action, argparse._StoreConstAction):
# "is" rather than "==": a store_false default of 0 equals False
value = value is action.const
if isinstance(value, bool):
value = str(value).lower()
return value
def already_on_command_line(
existing_args_list, potential_command_line_args, prefix_chars
):
"""Utility method for checking if any of the potential_command_line_args is
already present in existing_args.
Returns:
bool: already on command line?
"""
arg_names = []
for arg_string in existing_args_list:
if arg_string == "--":
break
if arg_string and arg_string[0] in prefix_chars and "=" in arg_string:
option_string, explicit_arg = arg_string.split("=", 1)
arg_names.append(option_string)
else:
arg_names.append(arg_string)
return any(
potential_arg in arg_names for potential_arg in potential_command_line_args
)
# NOTE: Aliases below are not auto-documented. This could be improved by updating
# to latest version of pydoctor when https://github.com/twisted/pydoctor/pull/414
# has been merged, which would allow aliases to be documented automatically.
# wrap ArgumentParser's add_argument(..) method with the one above
argparse._ActionsContainer.original_add_argument_method = (
argparse._ActionsContainer.add_argument
)
argparse._ActionsContainer.add_argument = add_argument
# add all public classes and constants from argparse module's namespace to this
# module's namespace so that the 2 modules are truly interchangeable
Action = argparse.Action
ArgumentDefaultsHelpFormatter = argparse.ArgumentDefaultsHelpFormatter
ArgumentError = argparse.ArgumentError
ArgumentTypeError = argparse.ArgumentTypeError
FileType = argparse.FileType
HelpFormatter = argparse.HelpFormatter
MetavarTypeHelpFormatter = argparse.MetavarTypeHelpFormatter
Namespace = argparse.Namespace
RawDescriptionHelpFormatter = argparse.RawDescriptionHelpFormatter
RawTextHelpFormatter = argparse.RawTextHelpFormatter
ONE_OR_MORE = argparse.ONE_OR_MORE
OPTIONAL = argparse.OPTIONAL
PARSER = argparse.PARSER
REMAINDER = argparse.REMAINDER
SUPPRESS = argparse.SUPPRESS
ZERO_OR_MORE = argparse.ZERO_OR_MORE
# deprecated PEP-8 incompatible API names.
initArgumentParser = init_argument_parser
getArgumentParser = get_argument_parser
getArgParser = get_argument_parser
getParser = get_argument_parser
# create shorter aliases for the key methods and class names
get_arg_parser = get_argument_parser
get_parser = get_argument_parser
ArgParser = ArgumentParser
Parser = ArgumentParser
argparse._ActionsContainer.add_arg = argparse._ActionsContainer.add_argument
argparse._ActionsContainer.add = argparse._ActionsContainer.add_argument
ArgumentParser.parse = ArgumentParser.parse_args
ArgumentParser.parse_known = ArgumentParser.parse_known_args
RawFormatter = RawDescriptionHelpFormatter
DefaultsFormatter = ArgumentDefaultsHelpFormatter
DefaultsRawFormatter = ArgumentDefaultsRawHelpFormatter
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7560594
configargparse-1.9.0/setup.cfg 0000644 0001751 0001751 00000000046 15270233512 016002 0 ustar 00runner runner [egg_info]
tag_build =
tag_date = 0
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9304025
configargparse-1.9.0/setup.py 0000644 0001751 0001751 00000010246 15270233507 015702 0 ustar 00runner runner import logging
import os
import sys
try:
from setuptools import setup
except ImportError:
print("WARNING: setuptools not installed. Will try using distutils instead..")
from distutils.core import setup
def launch_http_server(directory):
assert os.path.isdir(directory)
try:
try:
from SimpleHTTPServer import SimpleHTTPRequestHandler
except ImportError:
from http.server import SimpleHTTPRequestHandler
try:
import SocketServer
except ImportError:
import socketserver as SocketServer
import socket
for port in [80] + list(range(8000, 8100)):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", port))
s.close()
except socket.error as e:
logging.debug("Can't use port %d: %s" % (port, e.strerror))
continue
print(
"HTML coverage report now available at http://{}{}".format(
socket.gethostname(), (":%s" % port) if port != 80 else ""
)
)
os.chdir(directory)
SocketServer.TCPServer(("", port), SimpleHTTPRequestHandler).serve_forever()
else:
logging.debug("All network port. ")
except Exception as e:
logging.error(
"ERROR: while starting an HTTP server to serve the coverage report: %s" % e
)
command = sys.argv[-1]
if command == "publish":
os.system("rm -rf dist")
os.system("python3 setup.py sdist")
os.system("python3 setup.py bdist_wheel")
os.system(
"twine check dist/*"
) # check for formatting or other issues that would cause twine upload to error out
os.system("twine upload dist/*whl dist/*gz")
sys.exit()
elif command == "coverage":
try:
import coverage
except:
sys.exit("coverage.py not installed (pip install --user coverage)")
setup_py_path = os.path.abspath(__file__)
os.system("coverage run --source=configargparse " + setup_py_path + " test")
os.system("coverage report")
os.system("coverage html")
print("Done computing coverage")
launch_http_server(directory="htmlcov")
sys.exit()
long_description = ""
if command not in ["test", "coverage"]:
long_description = open("README.md").read()
install_requires = []
tests_require = [
"black",
"mock",
"toml",
"PyYAML",
"pytest",
"pytest-cov",
"pytest-subtests",
]
setup(
name="ConfigArgParse",
use_scm_version={"version_scheme": "no-guess-dev"},
setup_requires=["setuptools_scm"],
description="A drop-in replacement for argparse that allows options to "
"also be set via config files and/or environment variables.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/bw2/ConfigArgParse",
py_modules=["configargparse"],
include_package_data=True,
license="MIT",
keywords="options, argparse, ConfigArgParse, config, environment variables, "
"envvars, ENV, environment, optparse, YAML, INI",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
test_suite="tests",
python_requires=">=3.6",
install_requires=install_requires,
tests_require=tests_require,
extras_require={
"toml": ["toml"],
"yaml": ["PyYAML"],
"test": tests_require,
},
)
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144649.7551515
configargparse-1.9.0/tests/ 0000755 0001751 0001751 00000000000 15270233512 015323 5 ustar 00runner runner ././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1793144646.9304025
configargparse-1.9.0/tests/__init__.py 0000644 0001751 0001751 00000000056 15270233507 017441 0 ustar 00runner runner #!/usr/bin/env python
# -*- coding: utf-8 -*-
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1793144646.931062
configargparse-1.9.0/tests/test_configargparse.py 0000644 0001751 0001751 00000561405 15270233507 021745 0 ustar 00runner runner import argparse
from collections import OrderedDict
import configargparse
from contextlib import contextmanager
import functools
import inspect
import json
import logging
import os
import pathlib
import sys
import tempfile
import traceback
import types
import unittest
from unittest import mock
import warnings
import textwrap
from io import BytesIO, StringIO
if sys.version_info >= (3, 10):
OPTIONAL_ARGS_STRING = "options"
else:
OPTIONAL_ARGS_STRING = "optional arguments"
# In Python 3.13+, short option metavars are no longer repeated
if sys.version_info >= (3, 13):
SHORT_OPT_METAVAR = "" # e.g., "-g, --my-cfg-file MY_CFG_FILE"
else:
SHORT_OPT_METAVAR = "(?: {metavar})?" # e.g., "-g MY_CFG_FILE, --my-cfg-file MY_CFG_FILE" or "-g, --my-cfg-file MY_CFG_FILE"
# set COLUMNS to get expected wrapping
os.environ["COLUMNS"] = "80"
# enable logging to simplify debugging
logger = logging.getLogger()
logger.level = logging.DEBUG
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
def replace_error_method(arg_parser):
"""Swap out arg_parser's error(..) method so that instead of calling
sys.exit(..) it just raises an error.
"""
def error_method(self, message):
raise argparse.ArgumentError(None, message)
def exit_method(self, status, message=None):
self._exit_method_called = True
arg_parser._exit_method_called = False
arg_parser.error = types.MethodType(error_method, arg_parser)
arg_parser.exit = types.MethodType(exit_method, arg_parser)
return arg_parser
@contextmanager
def captured_output():
"""
swap stdout and stderr for StringIO so we can do asserts on outputs.
"""
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
class TestCase(unittest.TestCase):
def initParser(self, *args, **kwargs):
p = configargparse.ArgParser(*args, **kwargs)
self.parser = replace_error_method(p)
self.add_arg = self.parser.add_argument
self.parse = self.parser.parse_args
self.parse_known = self.parser.parse_known_args
self.format_values = self.parser.format_values
self.format_help = self.parser.format_help
return self.parser
def assertParseArgsRaises(self, regex, args, **kwargs):
self.assertRaisesRegex(
argparse.ArgumentError, regex, self.parse, args=args, **kwargs
)
class TestBasicUseCases(TestCase):
def setUp(self):
self.initParser(args_for_setting_config_path=[])
def testBasicCase1(self):
## Test command line and config file values
self.add_arg("filenames", nargs="+", help="positional arg")
self.add_arg("-x", "--arg-x", action="store_true")
self.add_arg("-y", "--arg-y", dest="y1", type=int, required=True)
self.add_arg("--arg-z", action="append", type=float, required=True)
if sys.version_info >= (3, 9):
self.add_arg("--foo", action=argparse.BooleanOptionalAction, default=False)
else:
self.add_arg("--foo", action="store_true", default=False)
# make sure required args are enforced
self.assertParseArgsRaises(
(
"too few arg"
if sys.version_info.major < 3
else "the following arguments are required"
),
args="",
)
self.assertParseArgsRaises(
(
"argument -y/--arg-y is required"
if sys.version_info.major < 3
else "the following arguments are required: -y/--arg-y"
),
args="-x --arg-z 11 file1.txt",
)
self.assertParseArgsRaises(
(
"argument --arg-z is required"
if sys.version_info.major < 3
else "the following arguments are required: --arg-z"
),
args="file1.txt file2.txt file3.txt -x -y 1",
)
# check values after setting args on command line
ns = self.parse(
args="file1.txt --arg-x -y 3 --arg-z 10 --foo", config_file_contents=""
)
self.assertListEqual(ns.filenames, ["file1.txt"])
self.assertEqual(ns.arg_x, True)
self.assertEqual(ns.y1, 3)
self.assertEqual(ns.arg_z, [10])
self.assertEqual(ns.foo, True)
self.assertRegex(
self.format_values(),
"Command Line Args: file1.txt --arg-x -y 3 --arg-z 10",
)
# check values after setting args in config file
ns = self.parse(
args="file1.txt file2.txt",
config_file_contents="""
# set all required args in config file
arg-x = True
arg-y = 10
arg-z = 30
arg-z = 40
foo = True
""",
)
self.assertListEqual(ns.filenames, ["file1.txt", "file2.txt"])
self.assertEqual(ns.arg_x, True)
self.assertEqual(ns.y1, 10)
self.assertEqual(ns.arg_z, [40])
self.assertEqual(ns.foo, True)
self.assertRegex(
self.format_values(),
"Command Line Args: \\s+ file1.txt file2.txt\n"
"Config File \\(method arg\\):\n"
" arg-x: \\s+ True\n"
" arg-y: \\s+ 10\n"
" arg-z: \\s+ 40\n"
" foo: \\s+ True\n",
)
# check values after setting args in both command line and config file
ns = self.parse(
args="file1.txt file2.txt --arg-x -y 3 --arg-z 100 ",
config_file_contents="""arg-y = 31.5
arg-z = 30
foo = True
""",
)
self.format_help()
self.format_values()
self.assertListEqual(ns.filenames, ["file1.txt", "file2.txt"])
self.assertEqual(ns.arg_x, True)
self.assertEqual(ns.y1, 3)
self.assertEqual(ns.arg_z, [100])
self.assertEqual(ns.foo, True)
self.assertRegex(
self.format_values(),
"Command Line Args: file1.txt file2.txt --arg-x -y 3 --arg-z 100",
)
def testBasicCase2(self, use_groups=False):
## Test command line, config file and env var values
default_config_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
default_config_file.flush()
p = self.initParser(
default_config_files=[
"/etc/settings.ini",
"/home/jeff/.user_settings",
default_config_file.name,
]
)
p.add_arg("vcf", nargs="+", help="Variant file(s)")
if not use_groups:
self.add_arg("--genome", help="Path to genome file", required=True)
self.add_arg("-v", dest="verbose", action="store_true")
self.add_arg("-g", "--my-cfg-file", required=True, is_config_file=True)
self.add_arg("-d", "--dbsnp", env_var="DBSNP_PATH")
self.add_arg(
"-f",
"--format",
choices=["BED", "MAF", "VCF", "WIG", "R"],
dest="fmt",
metavar="FRMT",
env_var="OUTPUT_FORMAT",
default="BED",
)
else:
g = p.add_argument_group(title="g1")
g.add_arg("--genome", help="Path to genome file", required=True)
g.add_arg("-v", dest="verbose", action="store_true")
g.add_arg("-g", "--my-cfg-file", required=True, is_config_file=True)
g = p.add_argument_group(title="g2")
g.add_arg("-d", "--dbsnp", env_var="DBSNP_PATH")
g.add_arg(
"-f",
"--format",
choices=["BED", "MAF", "VCF", "WIG", "R"],
dest="fmt",
metavar="FRMT",
env_var="OUTPUT_FORMAT",
default="BED",
)
# make sure required args are enforced
self.assertParseArgsRaises(
(
"too few arg"
if sys.version_info.major < 3
else "the following arguments are required: vcf, -g/--my-cfg-file"
),
args="--genome hg19",
)
self.assertParseArgsRaises(
r"Unable to open config file: file\.txt\. Error: .*No such file or director",
args="-g file.txt",
)
# check values after setting args on command line
config_file2 = tempfile.NamedTemporaryFile(mode="w", delete=False)
config_file2.flush()
ns = self.parse(args="--genome hg19 -g %s bla.vcf " % config_file2.name)
self.assertEqual(ns.genome, "hg19")
self.assertEqual(ns.verbose, False)
self.assertIsNone(ns.dbsnp)
self.assertEqual(ns.fmt, "BED")
self.assertListEqual(ns.vcf, ["bla.vcf"])
self.assertRegex(
self.format_values(),
"Command Line Args: --genome hg19 -g [^\\s]+ bla.vcf\n"
"Defaults:\n"
" --format: \\s+ BED\n",
)
# check precedence: args > env > config > default using the --format arg
default_config_file.write("--format MAF")
default_config_file.flush()
ns = self.parse(args="--genome hg19 -g %s f.vcf " % config_file2.name)
self.assertEqual(ns.fmt, "MAF")
self.assertRegex(
self.format_values(),
"Command Line Args: --genome hg19 -g [^\\s]+ f.vcf\n"
"Config File \\([^\\s]+\\):\n"
" --format: \\s+ MAF\n",
)
config_file2.write("--format VCF")
config_file2.flush()
ns = self.parse(args="--genome hg19 -g %s f.vcf " % config_file2.name)
self.assertEqual(ns.fmt, "VCF")
self.assertRegex(
self.format_values(),
"Command Line Args: --genome hg19 -g [^\\s]+ f.vcf\n"
"Config File \\([^\\s]+\\):\n"
" --format: \\s+ VCF\n",
)
ns = self.parse(
env_vars={"OUTPUT_FORMAT": "R", "DBSNP_PATH": "/a/b.vcf"},
args="--genome hg19 -g %s f.vcf " % config_file2.name,
)
self.assertEqual(ns.fmt, "R")
self.assertEqual(ns.dbsnp, "/a/b.vcf")
self.assertRegex(
self.format_values(),
"Command Line Args: --genome hg19 -g [^\\s]+ f.vcf\n"
"Environment Variables:\n"
" DBSNP_PATH: \\s+ /a/b.vcf\n"
" OUTPUT_FORMAT: \\s+ R\n",
)
ns = self.parse(
env_vars={
"OUTPUT_FORMAT": "R",
"DBSNP_PATH": "/a/b.vcf",
"ANOTHER_VAR": "something",
},
args="--genome hg19 -g %s --format WIG f.vcf" % config_file2.name,
)
self.assertEqual(ns.fmt, "WIG")
self.assertEqual(ns.dbsnp, "/a/b.vcf")
self.assertRegex(
self.format_values(),
"Command Line Args: --genome hg19 -g [^\\s]+ --format WIG f.vcf\n"
"Environment Variables:\n"
" DBSNP_PATH: \\s+ /a/b.vcf\n",
)
if not use_groups:
short_g = SHORT_OPT_METAVAR.format(metavar="MY_CFG_FILE")
short_d = SHORT_OPT_METAVAR.format(metavar="DBSNP")
short_f = SHORT_OPT_METAVAR.format(metavar="FRMT")
self.assertRegex(
self.format_help(),
"usage: .*\\s+\\[-h\\] --genome GENOME \\[-v\\] -g MY_CFG_FILE\n?"
"\\s+\\[-d DBSNP\\]\\s+\\[-f FRMT\\]\\s+vcf \\[vcf ...\\]\n\n"
"positional arguments:\n"
" vcf \\s+ Variant file\\(s\\)\n\n"
"%s:\n"
" -h, --help \\s+ show this help message and exit\n"
" --genome GENOME \\s+ Path to genome file\n"
" -v\n"
f" -g{short_g}, --my-cfg-file MY_CFG_FILE\n"
f" -d{short_d}, --dbsnp DBSNP\\s+\\[env var: DBSNP_PATH\\]\n"
f" -f{short_f}, --format FRMT\\s+\\[env var: OUTPUT_FORMAT\\]\n\n"
% OPTIONAL_ARGS_STRING
+ 7 * r"(.+\s*)",
)
else:
short_g = SHORT_OPT_METAVAR.format(metavar="MY_CFG_FILE")
short_d = SHORT_OPT_METAVAR.format(metavar="DBSNP")
short_f = SHORT_OPT_METAVAR.format(metavar="FRMT")
self.assertRegex(
self.format_help(),
"usage: .*\\s+\\[-h\\] --genome GENOME \\[-v\\] -g MY_CFG_FILE\n?"
"\\s+\\[-d DBSNP\\]\\s+\\[-f FRMT\\]\\s+vcf \\[vcf ...\\]\n\n"
"positional arguments:\n"
" vcf \\s+ Variant file\\(s\\)\n\n"
"%s:\n"
" -h, --help \\s+ show this help message and exit\n\n"
"g1:\n"
" --genome GENOME \\s+ Path to genome file\n"
" -v\n"
f" -g{short_g}, --my-cfg-file MY_CFG_FILE\n\n"
"g2:\n"
f" -d{short_d}, --dbsnp DBSNP\\s+\\[env var: DBSNP_PATH\\]\n"
f" -f{short_f}, --format FRMT\\s+\\[env var: OUTPUT_FORMAT\\]\n\n"
% OPTIONAL_ARGS_STRING
+ 7 * r"(.+\s*)",
)
self.assertParseArgsRaises(
"invalid choice: 'ZZZ'",
args="--genome hg19 -g %s --format ZZZ f.vcf" % config_file2.name,
)
self.assertParseArgsRaises(
"unrecognized arguments: --bla",
args="--bla --genome hg19 -g %s f.vcf" % config_file2.name,
)
default_config_file.close()
config_file2.close()
def testBasicCase2_WithGroups(self):
self.testBasicCase2(use_groups=True)
def testCustomOpenFunction(self):
expected_output = "dummy open called"
def dummy_open(p):
print(expected_output)
return open(p)
self.initParser(config_file_open_func=dummy_open)
self.add_arg("--config", is_config_file=True)
self.add_arg("--arg1", default=1, type=int)
with tempfile.NamedTemporaryFile(mode="w", delete=False) as config_file:
config_file.write("arg1 2")
config_file_path = config_file.name
with captured_output() as (out, _):
args = self.parse("--config {}".format(config_file_path))
self.assertTrue(hasattr(args, "arg1"))
self.assertEqual(args.arg1, 2)
output = out.getvalue().strip()
self.assertEqual(output, expected_output)
def testIgnoreHelpArgs(self):
p = self.initParser()
self.add_arg("--arg1")
args, _ = self.parse_known("--arg2 --help", ignore_help_args=True)
self.assertEqual(args.arg1, None)
self.add_arg("--arg2")
args, _ = self.parse_known("--arg2 3 --help", ignore_help_args=True)
self.assertEqual(args.arg2, "3")
self.assertRaisesRegex(
TypeError,
"exit",
self.parse_known,
"--arg2 3 --help",
ignore_help_args=False,
)
def testPositionalAndConfigVarLists(self):
self.initParser()
self.add_arg("a")
self.add_arg("-x", "--arg", nargs="+")
ns = self.parse(
"positional_value",
config_file_contents="""arg = [Shell, someword, anotherword]""",
)
self.assertEqual(ns.arg, ["Shell", "someword", "anotherword"])
self.assertEqual(ns.a, "positional_value")
def testCustomActionWithNargsAndConfigVarList(self):
# https://github.com/bw2/ConfigArgParse/issues/354
class CustomAction(configargparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
self.initParser()
self.add_arg("-x", "--arg", nargs="+", action=CustomAction)
ns = self.parse("", config_file_contents="""arg = [foo, bar]""")
self.assertEqual(ns.arg, ["foo", "bar"])
def testCustomActionWithoutNargsAndConfigVarList(self):
class CustomAction(configargparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
self.initParser()
self.add_arg("-x", "--arg", action=CustomAction)
self.assertParseArgsRaises(
"arg can't be set to a list",
args="",
config_file_contents="""arg = [foo, bar]""",
)
def testMutuallyExclusiveArgs(self):
config_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
p = self.parser
g = p.add_argument_group(title="group1")
g.add_arg("--genome", help="Path to genome file", required=True)
g.add_arg("-v", dest="verbose", action="store_true")
g = p.add_mutually_exclusive_group(required=True)
g.add_arg("-f1", "--type1-cfg-file", is_config_file=True)
g.add_arg("-f2", "--type2-cfg-file", is_config_file=True)
g = p.add_mutually_exclusive_group(required=True)
g.add_arg(
"-f",
"--format",
choices=["BED", "MAF", "VCF", "WIG", "R"],
dest="fmt",
metavar="FRMT",
env_var="OUTPUT_FORMAT",
default="BED",
)
g.add_arg(
"-b",
"--bam",
dest="fmt",
action="store_const",
const="BAM",
env_var="BAM_FORMAT",
)
ns = self.parse(args="--genome hg19 -f1 %s --bam" % config_file.name)
self.assertEqual(ns.genome, "hg19")
self.assertEqual(ns.verbose, False)
self.assertEqual(ns.fmt, "BAM")
ns = self.parse(
env_vars={"BAM_FORMAT": "true"},
args="--genome hg19 -f1 %s" % config_file.name,
)
self.assertEqual(ns.genome, "hg19")
self.assertEqual(ns.verbose, False)
self.assertEqual(ns.fmt, "BAM")
self.assertRegex(
self.format_values(),
"Command Line Args: --genome hg19 -f1 [^\\s]+\n"
"Environment Variables:\n"
" BAM_FORMAT: \\s+ true\n"
"Defaults:\n"
" --format: \\s+ BED\n",
)
short_f1 = SHORT_OPT_METAVAR.format(metavar="TYPE1_CFG_FILE")
short_f2 = SHORT_OPT_METAVAR.format(metavar="TYPE2_CFG_FILE")
short_f = SHORT_OPT_METAVAR.format(metavar="FRMT")
self.assertRegex(
self.format_help(),
r"usage: .*\s+\[-h\] --genome GENOME \[-v\]\s+\(-f1 TYPE1_CFG_FILE \|"
r"\s+-f2 TYPE2_CFG_FILE\)\s+\(-f FRMT \| -b\)\n\n"
"%s:\n"
" -h, --help show this help message and exit\n"
f" -f1{short_f1}, --type1-cfg-file TYPE1_CFG_FILE\n"
f" -f2{short_f2}, --type2-cfg-file TYPE2_CFG_FILE\n"
f" -f{short_f}, --format FRMT\\s+\\[env var: OUTPUT_FORMAT\\]\n"
" -b, --bam\\s+\\[env var: BAM_FORMAT\\]\n\n"
"group1:\n"
" --genome GENOME Path to genome file\n"
" -v\n\n" % OPTIONAL_ARGS_STRING,
)
config_file.close()
def testMutuallyExclusiveArgsOverriddenByOtherSources(self):
# a config file or env var value for one member of a mutually exclusive
# group is overridden by a different member set in a higher priority
# source, instead of clashing with it (issue #164)
def init_parser(**kwargs):
p = self.initParser(**kwargs)
g = p.add_mutually_exclusive_group(required=True)
g.add_arg(
"-m",
"--mega",
dest="mode",
action="store_const",
const="mega",
env_var="MEGA",
)
g.add_arg(
"-g",
"--giga",
dest="mode",
action="store_const",
const="giga",
env_var="GIGA",
)
return p
init_parser()
ns = self.parse(args=[], config_file_contents="mega = true", env_vars={})
self.assertEqual(ns.mode, "mega")
# command line overrides config file
ns = self.parse(
args=["--giga"], config_file_contents="mega = true", env_vars={}
)
self.assertEqual(ns.mode, "giga")
self.assertEqual(self.format_values(), "Command Line Args: --giga\n")
ns = self.parse(args=["-g"], config_file_contents="mega = true", env_vars={})
self.assertEqual(ns.mode, "giga")
# command line overrides env var
ns = self.parse(args=["--giga"], env_vars={"MEGA": "true"})
self.assertEqual(ns.mode, "giga")
self.assertEqual(self.format_values(), "Command Line Args: --giga\n")
# env var overrides config file
ns = self.parse(
args=[], config_file_contents="mega = true", env_vars={"GIGA": "true"}
)
self.assertEqual(ns.mode, "giga")
# a config file given on the command line overrides a default config file
with tempfile.TemporaryDirectory() as tmp_dir:
default_config_path = os.path.join(tmp_dir, "default.ini")
with open(default_config_path, "w") as f:
f.write("mega = true\n")
user_config_path = os.path.join(tmp_dir, "user.ini")
with open(user_config_path, "w") as f:
f.write("giga = true\n")
init_parser(default_config_files=[default_config_path])
self.add_arg("-c", "--config", is_config_file=True)
ns = self.parse(args=[], env_vars={})
self.assertEqual(ns.mode, "mega")
ns = self.parse(args=["-c", user_config_path], env_vars={})
self.assertEqual(ns.mode, "giga")
# members set together within a single source still conflict
init_parser()
self.assertParseArgsRaises(
"not allowed with argument",
args=[],
config_file_contents="mega = true\ngiga = true",
env_vars={},
)
self.assertParseArgsRaises(
"not allowed with argument",
args=[],
env_vars={"MEGA": "true", "GIGA": "true"},
)
self.assertParseArgsRaises(
"not allowed with argument", args=["--mega", "--giga"], env_vars={}
)
def testMutuallyExclusiveBoolArgsOverriddenByCommandLine(self):
# the --feature / --no-feature pattern from issue #164, with the
# mutually exclusive group inside an argument group
g = self.parser.add_argument_group(title="features")
g = g.add_mutually_exclusive_group()
g.add_arg("--feature", dest="feature", action="store_true")
g.add_arg("--no-feature", dest="feature", action="store_false")
ns = self.parse(args=[], config_file_contents="feature = true", env_vars={})
self.assertEqual(ns.feature, True)
ns = self.parse(
args=["--no-feature"], config_file_contents="feature = true", env_vars={}
)
self.assertEqual(ns.feature, False)
ns = self.parse(
args=["--feature"], config_file_contents="no-feature = true", env_vars={}
)
self.assertEqual(ns.feature, True)
def testSubParsers(self):
config_file1 = tempfile.NamedTemporaryFile(mode="w", delete=False)
config_file1.write("--i = B")
config_file1.flush()
config_file2 = tempfile.NamedTemporaryFile(mode="w", delete=False)
config_file2.write("p = 10")
config_file2.flush()
parser = configargparse.ArgumentParser(prog="myProg")
subparsers = parser.add_subparsers(title="actions")
parent_parser = configargparse.ArgumentParser(add_help=False)
parent_parser.add_argument(
"-p", "--p", type=int, required=True, help="set db parameter"
)
create_p = subparsers.add_parser(
"create", parents=[parent_parser], help="create the orbix environment"
)
create_p.add_argument("--i", env_var="INIT", choices=["A", "B"], default="A")
create_p.add_argument("-config", is_config_file=True)
update_p = subparsers.add_parser(
"update", parents=[parent_parser], help="update the orbix environment"
)
update_p.add_argument("-config2", is_config_file=True, required=True)
ns = parser.parse_args(args="create -p 2 -config " + config_file1.name)
self.assertEqual(ns.p, 2)
self.assertEqual(ns.i, "B")
ns = parser.parse_args(args="update -config2 " + config_file2.name)
self.assertEqual(ns.p, 10)
config_file1.close()
config_file2.close()
def testSubParserEnvVar(self):
"""Test that env vars work with subparsers (issue #350)."""
parser = configargparse.ArgumentParser(auto_env_var_prefix="")
parser.add_argument("--tenant", env_var="TENANT", required=True)
subparsers = parser.add_subparsers(dest="action")
appliance_parser = subparsers.add_parser("appliance")
appliance_parser.add_argument("--token", env_var="TOKEN", required=True)
# Test parent parser env var via env_vars param
ns = parser.parse_args(
args=["appliance", "--token", "test-token"],
env_vars={"TENANT": "test-tenant"},
)
self.assertEqual(ns.tenant, "test-tenant")
self.assertEqual(ns.token, "test-token")
self.assertEqual(ns.action, "appliance")
# Test both parent and subparser env vars via real os.environ
os.environ["TENANT"] = "test-tenant"
os.environ["TOKEN"] = "test-token"
try:
ns = parser.parse_args(args=["appliance"])
self.assertEqual(ns.tenant, "test-tenant")
self.assertEqual(ns.token, "test-token")
self.assertEqual(ns.action, "appliance")
finally:
del os.environ["TENANT"]
del os.environ["TOKEN"]
def testAddArgsErrors(self):
self.assertRaisesRegex(
ValueError,
"arg with "
"is_write_out_config_file_arg=True can't also have "
"is_config_file_arg=True",
self.add_arg,
"-x",
"--X",
is_config_file=True,
is_write_out_config_file_arg=True,
)
self.assertRaisesRegex(
ValueError,
"arg with is_write_out_config_file_arg=True must have action='store'",
self.add_arg,
"-y",
"--Y",
action="append",
is_write_out_config_file_arg=True,
)
def testConfigFileSyntax(self):
self.add_arg("-x", required=True, type=int)
self.add_arg("--y", required=True, type=float)
self.add_arg("--z")
self.add_arg("--c")
self.add_arg("--b", action="store_true")
self.add_arg("--a", action="append", type=int)
self.add_arg(
"--m",
action="append",
nargs=3,
metavar=("", "", ""),
)
ns = self.parse(
args="-x 1",
env_vars={},
config_file_contents="""
#inline comment 1
# inline comment 2
# inline comment 3
;inline comment 4
; inline comment 5
;inline comment 6
--- # separator 1
------------- # separator 2
y=1.1
y = 2.1
y= 3.1 # with comment
y= 4.1 ; with comment
---
y:5.1
y : 6.1
y: 7.1 # with comment
y: 8.1 ; with comment
---
y \t 9.1
y 10.1
y 11.1 # with comment
y 12.1 ; with comment
---
b
b = True
b: True
----
a = 33
---
z z 1
---
m = [[1, 2, 3], [4, 5, 6]]
""",
)
self.assertEqual(ns.x, 1)
self.assertEqual(ns.y, 12.1)
self.assertEqual(ns.z, "z 1")
self.assertIsNone(ns.c)
self.assertEqual(ns.b, True)
self.assertEqual(ns.a, [33])
self.assertRegex(
self.format_values(),
"Command Line Args: \\s+ -x 1\n"
"Config File \\(method arg\\):\n"
" y: \\s+ 12.1\n"
" b: \\s+ True\n"
" a: \\s+ 33\n"
" z: \\s+ z 1\n",
)
self.assertEqual(ns.m, [["1", "2", "3"], ["4", "5", "6"]])
# -x is not a long arg so can't be set via config file
self.assertParseArgsRaises(
(
"argument -x is required"
if sys.version_info.major < 3
else "the following arguments are required: -x, --y"
),
args="",
config_file_contents="-x 3",
)
self.assertParseArgsRaises(
"invalid float value: 'abc'", args="-x 5", config_file_contents="y: abc"
)
self.assertParseArgsRaises(
(
"argument --y is required"
if sys.version_info.major < 3
else "the following arguments are required: --y"
),
args="-x 5",
config_file_contents="z: 1",
)
# test unknown config file args
self.assertParseArgsRaises(
"bla", args="-x 1 --y 2.3", config_file_contents="bla=3"
)
ns, args = self.parse_known(
"-x 10 --y 3.8", config_file_contents="bla=3", env_vars={"bla": "2"}
)
self.assertListEqual(args, ["--bla=3"])
self.initParser(ignore_unknown_config_file_keys=False)
ns, args = self.parse_known(
args="-x 1", config_file_contents="bla=3", env_vars={"bla": "2"}
)
self.assertEqual(set(args), {"--bla=3", "-x", "1"})
def testQuotedArgumentValues(self):
self.initParser()
self.add_arg("-a")
self.add_arg("--b")
self.add_arg("-c")
self.add_arg("--d")
self.add_arg("-e")
self.add_arg("-q")
self.add_arg("--quotes")
# sys.argv equivalent of -a="1" --b "1" -c= --d "" -e=: -q "\"'" --quotes "\"'"
ns = self.parse(
args=[
"-a=1",
"--b",
"1",
"-c=",
"--d",
"",
"-e=:",
"-q",
"\"'",
"--quotes",
"\"'",
],
env_vars={},
config_file_contents="",
)
self.assertEqual(ns.a, "1")
self.assertEqual(ns.b, "1")
self.assertEqual(ns.c, "")
self.assertEqual(ns.d, "")
self.assertEqual(ns.e, ":")
self.assertEqual(ns.q, "\"'")
self.assertEqual(ns.quotes, "\"'")
def testQuotedConfigFileValues(self):
self.initParser()
self.add_arg("--a")
self.add_arg("--b")
self.add_arg("--c")
ns = self.parse(
args="",
env_vars={},
config_file_contents="""
a="1"
b=:
c=
""",
)
self.assertEqual(ns.a, "1")
self.assertEqual(ns.b, ":")
self.assertEqual(ns.c, "")
def testBooleanValuesCanBeExpressedAsNumbers(self):
self.initParser()
store_true_env_var_name = "STORE_TRUE"
self.add_arg(
"--boolean_store_true", action="store_true", env_var=store_true_env_var_name
)
result_namespace = self.parse(
"", config_file_contents="""boolean_store_true = 1"""
)
self.assertTrue(result_namespace.boolean_store_true)
result_namespace = self.parse(
"", config_file_contents="""boolean_store_true = 0"""
)
self.assertFalse(result_namespace.boolean_store_true)
result_namespace = self.parse("", env_vars={store_true_env_var_name: "1"})
self.assertTrue(result_namespace.boolean_store_true)
result_namespace = self.parse("", env_vars={store_true_env_var_name: "0"})
self.assertFalse(result_namespace.boolean_store_true)
self.initParser()
store_false_env_var_name = "STORE_FALSE"
self.add_arg(
"--boolean_store_false",
action="store_false",
env_var=store_false_env_var_name,
)
result_namespace = self.parse(
"", config_file_contents="""boolean_store_false = 1"""
)
self.assertFalse(result_namespace.boolean_store_false)
result_namespace = self.parse(
"", config_file_contents="""boolean_store_false = 0"""
)
self.assertTrue(result_namespace.boolean_store_false)
result_namespace = self.parse("", env_vars={store_false_env_var_name: "1"})
self.assertFalse(result_namespace.boolean_store_false)
result_namespace = self.parse("", env_vars={store_false_env_var_name: "0"})
self.assertTrue(result_namespace.boolean_store_false)
def testConfigOrEnvValueErrors(self):
# error should occur when a flag arg is set to something other than "true" or "false"
self.initParser()
self.add_arg("--height", env_var="HEIGHT", required=True)
self.add_arg("--do-it", dest="x", env_var="FLAG1", action="store_true")
self.add_arg("--dont-do-it", dest="y", env_var="FLAG2", action="store_false")
ns = self.parse("", env_vars={"HEIGHT": "tall", "FLAG1": "yes"})
self.assertEqual(ns.height, "tall")
self.assertEqual(ns.x, True)
ns = self.parse("", env_vars={"HEIGHT": "tall", "FLAG2": "yes"})
self.assertEqual(ns.y, False)
ns = self.parse("", env_vars={"HEIGHT": "tall", "FLAG2": "no"})
self.assertEqual(ns.y, True)
# error should occur when flag arg is given a value
self.initParser()
self.add_arg("-v", "--verbose", env_var="VERBOSE", action="store_true")
self.assertParseArgsRaises(
"Unexpected value for VERBOSE: 'bla'. "
"Expecting 'true', 'false', 'yes', 'no', 'on', 'off', '1' or '0'",
args="",
env_vars={"VERBOSE": "bla"},
)
ns = self.parse(
"", config_file_contents="verbose=true", env_vars={"HEIGHT": "true"}
)
self.assertEqual(ns.verbose, True)
ns = self.parse("", config_file_contents="verbose", env_vars={"HEIGHT": "true"})
self.assertEqual(ns.verbose, True)
ns = self.parse("", env_vars={"HEIGHT": "true", "VERBOSE": "true"})
self.assertEqual(ns.verbose, True)
ns = self.parse("", env_vars={"HEIGHT": "true", "VERBOSE": "false"})
self.assertEqual(ns.verbose, False)
ns = self.parse(
"", config_file_contents="--verbose", env_vars={"HEIGHT": "true"}
)
self.assertEqual(ns.verbose, True)
# error should occur is non-append arg is given a list value
self.initParser()
self.add_arg("-f", "--file", env_var="FILES", action="append", type=int)
ns = self.parse("", env_vars={"file": "[1,2,3]", "VERBOSE": "true"})
self.assertIsNone(ns.file)
def testValuesStartingWithDash(self):
self.initParser()
self.add_arg("--arg0")
self.add_arg("--arg1", env_var="ARG1")
self.add_arg("--arg2")
self.add_arg("--arg3", action="append")
self.add_arg("--arg4", action="append", env_var="ARG4")
self.add_arg("--arg5", action="append")
self.add_arg("--arg6")
ns = self.parse(
"--arg0=-foo --arg3=-foo --arg3=-bar --arg6=-test-more-dashes",
config_file_contents="arg2: -foo\narg5: [-foo, -bar]",
env_vars={"ARG1": "-foo", "ARG4": "[-foo, -bar]"},
)
self.assertEqual(ns.arg0, "-foo")
self.assertEqual(ns.arg1, "-foo")
self.assertEqual(ns.arg2, "-foo")
self.assertEqual(ns.arg3, ["-foo", "-bar"])
self.assertEqual(ns.arg4, ["-foo", "-bar"])
self.assertEqual(ns.arg5, ["-foo", "-bar"])
self.assertEqual(ns.arg6, "-test-more-dashes")
def testPriorityKnown(self):
self.initParser()
self.add_arg("--arg", env_var="ARG")
ns = self.parse(
"--arg command_line_val",
config_file_contents="arg: config_val",
env_vars={"ARG": "env_val"},
)
self.assertEqual(ns.arg, "command_line_val")
ns = self.parse(
"--arg=command_line_val",
config_file_contents="arg: config_val",
env_vars={"ARG": "env_val"},
)
self.assertEqual(ns.arg, "command_line_val")
ns = self.parse(
"", config_file_contents="arg: config_val", env_vars={"ARG": "env_val"}
)
self.assertEqual(ns.arg, "env_val")
def testPriorityUnknown(self):
self.initParser()
ns, args = self.parse_known(
"--arg command_line_val",
config_file_contents="arg: config_val",
env_vars={"arg": "env_val"},
)
self.assertListEqual(args, ["--arg", "command_line_val"])
ns, args = self.parse_known(
"--arg=command_line_val",
config_file_contents="arg: config_val",
)
self.assertListEqual(args, ["--arg=command_line_val"])
def testAutoEnvVarPrefix(self):
self.initParser(auto_env_var_prefix="TEST_")
self.add_arg("-a", "--arg0", is_config_file_arg=True)
self.add_arg("-b", "--arg1", is_write_out_config_file_arg=True)
self.add_arg("-x", "--arg2", env_var="TEST2", type=int)
self.add_arg("-y", "--arg3", action="append", type=int)
self.add_arg("-z", "--arg4", required=True)
self.add_arg("-w", "--arg4-more", required=True)
ns = self.parse(
"",
env_vars={
"TEST_ARG0": "0",
"TEST_ARG1": "1",
"TEST_ARG2": "2",
"TEST2": "22",
"TEST_ARG4": "arg4_value",
"TEST_ARG4_MORE": "magic",
},
)
self.assertIsNone(ns.arg0)
self.assertIsNone(ns.arg1)
self.assertEqual(ns.arg2, 22)
self.assertEqual(ns.arg4, "arg4_value")
self.assertEqual(ns.arg4_more, "magic")
def testEnvVarLists(self):
self.initParser()
self.add_arg("-x", "--arg2", env_var="TEST2")
self.add_arg("-y", "--arg3", env_var="TEST3", type=int)
self.add_arg("-z", "--arg4", env_var="TEST4", nargs="+")
self.add_arg("-u", "--arg5", env_var="TEST5", nargs="+", type=int)
self.add_arg("--arg6", env_var="TEST6")
self.add_arg("--arg7", env_var="TEST7", action="append")
ns = self.parse(
"",
env_vars={
"TEST2": "22",
"TEST3": "22",
"TEST4": "[Shell, someword, anotherword]",
"TEST5": "[22, 99, 33]",
"TEST6": "[value6.1, value6.2, value6.3]",
"TEST7": "[value7.1, value7.2, value7.3]",
},
)
self.assertEqual(ns.arg2, "22")
self.assertEqual(ns.arg3, 22)
self.assertEqual(ns.arg4, ["Shell", "someword", "anotherword"])
self.assertEqual(ns.arg5, [22, 99, 33])
self.assertEqual(ns.arg6, "[value6.1, value6.2, value6.3]")
self.assertEqual(ns.arg7, ["value7.1", "value7.2", "value7.3"])
def testPositionalAndEnvVarLists(self):
self.initParser()
self.add_arg("a")
self.add_arg("-x", "--arg", env_var="TEST", nargs="+")
ns = self.parse(
"positional_value", env_vars={"TEST": "[Shell, someword, anotherword]"}
)
self.assertEqual(ns.arg, ["Shell", "someword", "anotherword"])
self.assertEqual(ns.a, "positional_value")
def testCounterCommandLine(self):
self.initParser()
self.add_arg("--verbose", "-v", action="count", default=0)
ns = self.parse(args="-v -v -v", env_vars={})
self.assertEqual(ns.verbose, 3)
ns = self.parse(args="-vvv", env_vars={})
self.assertEqual(ns.verbose, 3)
def testCounterConfigFile(self):
self.initParser()
self.add_arg("--verbose", "-v", action="count", default=0)
ns = self.parse(
args="",
env_vars={},
config_file_contents="""
verbose""",
)
self.assertEqual(ns.verbose, 1)
ns = self.parse(
args="",
env_vars={},
config_file_contents="""
verbose=3""",
)
self.assertEqual(ns.verbose, 3)
class TestMisc(TestCase):
# TODO test different action types with config file, env var
"""Test edge cases"""
def setUp(self):
self.initParser(args_for_setting_config_path=[])
@mock.patch("argparse.ArgumentParser.__init__")
def testKwrgsArePassedToArgParse(self, argparse_init):
kwargs_for_argparse = {"allow_abbrev": False, "whatever_other_arg": "something"}
parser = configargparse.ArgumentParser(
add_config_file_help=False, **kwargs_for_argparse
)
argparse_init.assert_called_with(parser, **kwargs_for_argparse)
def testGlobalInstances(self, name=None):
p = configargparse.getArgumentParser(name, prog="prog", usage="test")
self.assertEqual(p.usage, "test")
self.assertEqual(p.prog, "prog")
self.assertRaisesRegex(
ValueError,
"kwargs besides 'name' can only be passed in the first time",
configargparse.getArgumentParser,
name,
prog="prog",
)
p2 = configargparse.getArgumentParser(name)
self.assertEqual(p, p2)
def testGlobalInstances_WithName(self):
self.testGlobalInstances("name1")
self.testGlobalInstances("name2")
def testAddArguments_ArgValidation(self):
self.assertRaises(ValueError, self.add_arg, "positional", env_var="bla")
action = self.add_arg("positional")
self.assertIsNotNone(action)
self.assertEqual(action.dest, "positional")
def testAddArguments_IsConfigFilePathArg(self):
self.assertRaises(
ValueError, self.add_arg, "c", action="store_false", is_config_file=True
)
self.add_arg("-c", "--config", is_config_file=True)
self.add_arg("--x", required=True)
# verify parsing from config file
config_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
config_file.write("x=bla")
config_file.flush()
ns = self.parse(args="-c %s" % config_file.name)
self.assertEqual(ns.x, "bla")
def testConstructor_ConfigFileArgs(self):
# Test constructor args:
# args_for_setting_config_path
# config_arg_is_required
# config_arg_help_message
temp_cfg = tempfile.NamedTemporaryFile(mode="w", delete=False)
temp_cfg.write("genome=hg19")
temp_cfg.flush()
self.initParser(
args_for_setting_config_path=["-c", "--config"],
config_arg_is_required=True,
config_arg_help_message="my config file",
default_config_files=[temp_cfg.name],
)
self.add_arg("--genome", help="Path to genome file", required=True)
self.assertParseArgsRaises(
(
"argument -c/--config is required"
if sys.version_info.major < 3
else "arguments are required: -c/--config"
),
args="",
)
temp_cfg2 = tempfile.NamedTemporaryFile(mode="w", delete=False)
ns = self.parse("-c " + temp_cfg2.name)
self.assertEqual(ns.genome, "hg19")
# temp_cfg2 config file should override default config file values
temp_cfg2.write("genome=hg20")
temp_cfg2.flush()
ns = self.parse("-c " + temp_cfg2.name)
self.assertEqual(ns.genome, "hg20")
short_c = SHORT_OPT_METAVAR.format(metavar="CONFIG_FILE")
self.assertRegex(
self.format_help(),
r"usage: .*\s+\[-h\] -c CONFIG_FILE --genome GENOME\n\n"
r"%s:\n"
r" -h, --help\s+ show this help message and exit\n"
rf" -c{short_c}, --config CONFIG_FILE\s+ my config file\n"
r" --genome GENOME\s+ Path to genome file\n\n" % OPTIONAL_ARGS_STRING
+ 5 * r"(.+\s*)",
)
# just run print_values() to make sure it completes and returns None
output = StringIO()
self.assertIsNone(self.parser.print_values(file=output))
self.assertIn("Command Line Args:", output.getvalue())
# test ignore_unknown_config_file_keys=False
self.initParser(ignore_unknown_config_file_keys=False)
self.assertRaisesRegex(
argparse.ArgumentError,
"unrecognized arguments",
self.parse,
config_file_contents="arg1 = 3",
)
ns, args = self.parse_known(config_file_contents="arg1 = 3")
self.assertEqual(getattr(ns, "arg1", ""), "")
# test ignore_unknown_config_file_keys=True
self.initParser(ignore_unknown_config_file_keys=True)
ns = self.parse(args="", config_file_contents="arg1 = 3")
self.assertEqual(getattr(ns, "arg1", ""), "")
ns, args = self.parse_known(config_file_contents="arg1 = 3")
self.assertEqual(getattr(ns, "arg1", ""), "")
def test_AbbrevConfigFileArgs(self):
"""Tests that abbreviated values don't get pulled from config file."""
temp_cfg = tempfile.NamedTemporaryFile(mode="w", delete=False)
temp_cfg.write("a2a = 0.5\n")
temp_cfg.write("a3a = 0.5\n")
temp_cfg.flush()
self.initParser()
self.add_arg(
"-c",
"--config_file",
required=False,
is_config_file=True,
help="config file path",
)
self.add_arg("--hello", type=int, required=False)
command = "-c {} --hello 2".format(temp_cfg.name)
known, unknown = self.parse_known(command)
self.assertListEqual(unknown, ["--a2a=0.5", "--a3a=0.5"])
def test_FormatHelp(self):
self.initParser(
args_for_setting_config_path=["-c", "--config"],
config_arg_is_required=True,
config_arg_help_message="my config file",
default_config_files=["~/.myconfig"],
args_for_writing_out_config_file=["-w", "--write-config"],
)
self.add_arg("--arg1", help="Arg1 help text", required=True)
self.add_arg("--flag", help="Flag help text", action="store_true")
short_c = SHORT_OPT_METAVAR.format(metavar="CONFIG_FILE")
short_w = SHORT_OPT_METAVAR.format(metavar="CONFIG_OUTPUT_PATH")
self.assertRegex(
self.format_help(),
r"usage: .*\s+\[-h\] -c CONFIG_FILE\s+"
r"\[-w CONFIG_OUTPUT_PATH\]\s* --arg1\s+ARG1\s*\[--flag\]\s*"
"%s:\\s*"
"-h, --help \\s* show this help message and exit "
rf"-c{short_c}, --config CONFIG_FILE\s+my config file "
rf"-w{short_w}, --write-config CONFIG_OUTPUT_PATH takes "
r"the current command line args and writes them "
r"out to a config file at the given path, then exits "
r"--arg1 ARG1 Arg1 help text "
r"--flag Flag help text "
"Args that start with '--' can also be set in a "
r"config file \(~/.myconfig or specified via -c\). "
r"Config file syntax allows: key=value, flag=true, stuff=\[a,b,c\] "
r"\(for details, see syntax at https://goo.gl/R74nmi\). "
r"In general, command-line values override config file values "
r"which override defaults. ".replace(" ", r"\s*") % OPTIONAL_ARGS_STRING,
)
def test_FormatHelpProg(self):
self.initParser("format_help_prog")
self.assertRegex(self.format_help(), "usage: format_help_prog .*")
def test_FormatHelpProgLib(self):
parser = argparse.ArgumentParser("format_help_prog")
self.assertRegex(parser.format_help(), "usage: format_help_prog .*")
def testConstructor_WriteOutConfigFileArgs(self):
# Test constructor args:
# args_for_writing_out_config_file
# write_out_config_file_arg_help_message
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
self.initParser(
args_for_writing_out_config_file=["-w"],
write_out_config_file_arg_help_message="write config",
)
self.add_arg("-not-config-file-settable")
self.add_arg("--config-file-settable-arg", type=int)
self.add_arg("--config-file-settable-arg2", type=int, default=3)
self.add_arg("--config-file-settable-flag", action="store_true")
self.add_arg("--config-file-settable-custom")
self.add_arg("-l", "--config-file-settable-list", action="append")
# write out a config file
command_line_args = "-w %s " % cfg_f.name
command_line_args += "--config-file-settable-arg 1 "
command_line_args += "--config-file-settable-flag "
command_line_args += "--config-file-settable-custom custom_value "
command_line_args += "-l a -l b -l c -l d "
self.assertFalse(self.parser._exit_method_called)
ns = self.parse(command_line_args)
self.assertTrue(self.parser._exit_method_called)
cfg_f.seek(0)
expected_config_file_contents = "config-file-settable-arg = 1\n"
expected_config_file_contents += "config-file-settable-flag = true\n"
expected_config_file_contents += "config-file-settable-custom = custom_value\n"
expected_config_file_contents += "config-file-settable-list = [a, b, c, d]\n"
expected_config_file_contents += "config-file-settable-arg2 = 3\n"
self.assertEqual(cfg_f.read().strip(), expected_config_file_contents.strip())
self.assertRaisesRegex(
ValueError,
"Couldn't open / for writing:",
self.parse,
args=command_line_args + " -w /",
)
cfg_f.close()
def testConstructor_WriteOutConfigFileArgs2(self):
# Test constructor args:
# args_for_writing_out_config_file
# write_out_config_file_arg_help_message
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
self.initParser(
args_for_writing_out_config_file=["-w"],
write_out_config_file_arg_help_message="write config",
)
self.add_arg("-not-config-file-settable")
self.add_arg("-a", "--arg1", type=int, env_var="ARG1")
self.add_arg("-b", "--arg2", type=int, default=3)
self.add_arg("-c", "--arg3")
self.add_arg("-d", "--arg4")
self.add_arg("-e", "--arg5")
self.add_arg(
"--config-file-settable-flag", action="store_true", env_var="FLAG_ARG"
)
self.add_arg("-l", "--config-file-settable-list", action="append")
# write out a config file
command_line_args = "-w %s " % cfg_f.name
command_line_args += "-l a -l b -l c -l d "
self.assertFalse(self.parser._exit_method_called)
ns = self.parse(
command_line_args,
env_vars={"ARG1": "10", "FLAG_ARG": "true", "SOME_OTHER_ENV_VAR": "2"},
config_file_contents="arg3 = bla3\narg4 = bla4",
)
self.assertTrue(self.parser._exit_method_called)
cfg_f.seek(0)
expected_config_file_contents = "config-file-settable-list = [a, b, c, d]\n"
expected_config_file_contents += "arg1 = 10\n"
expected_config_file_contents += "config-file-settable-flag = true\n"
expected_config_file_contents += "arg3 = bla3\n"
expected_config_file_contents += "arg4 = bla4\n"
expected_config_file_contents += "arg2 = 3\n"
self.assertEqual(cfg_f.read().strip(), expected_config_file_contents.strip())
self.assertRaisesRegex(
ValueError,
"Couldn't open / for writing:",
self.parse,
args=command_line_args + " -w /",
)
cfg_f.close()
def testConstructor_WriteOutConfigFileArgsLong(self):
"""Test config writing with long version of arg
There was a bug where the long version of the
args_for_writing_out_config_file was being dumped into the resultant
output config file
"""
# Test constructor args:
# args_for_writing_out_config_file
# write_out_config_file_arg_help_message
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
self.initParser(
args_for_writing_out_config_file=["--write-config"],
write_out_config_file_arg_help_message="write config",
)
self.add_arg("-not-config-file-settable")
self.add_arg("--config-file-settable-arg", type=int)
self.add_arg("--config-file-settable-arg2", type=int, default=3)
self.add_arg("--config-file-settable-flag", action="store_true")
self.add_arg("-l", "--config-file-settable-list", action="append")
# write out a config file
command_line_args = "--write-config %s " % cfg_f.name
command_line_args += "--config-file-settable-arg 1 "
command_line_args += "--config-file-settable-flag "
command_line_args += "-l a -l b -l c -l d "
self.assertFalse(self.parser._exit_method_called)
ns = self.parse(command_line_args)
self.assertTrue(self.parser._exit_method_called)
cfg_f.seek(0)
expected_config_file_contents = "config-file-settable-arg = 1\n"
expected_config_file_contents += "config-file-settable-flag = true\n"
expected_config_file_contents += "config-file-settable-list = [a, b, c, d]\n"
expected_config_file_contents += "config-file-settable-arg2 = 3\n"
self.assertEqual(cfg_f.read().strip(), expected_config_file_contents.strip())
self.assertRaisesRegex(
ValueError,
"Couldn't open / for writing:",
self.parse,
args=command_line_args + " --write-config /",
)
cfg_f.close()
def testWriteOutConfigFileArg_CantBeSetFromAConfigFile(self):
"""A config file must not be able to trigger writing out a config file.
Doing so overwrites the given path and then exits, so a config file that
an attacker controls could otherwise destroy an arbitrary file without
the user passing any command line args at all.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--name", default="world")
self.assertParseArgsRaises(
"write-config can only be set on the command line",
args=[],
config_file_contents="name = attacker\nwrite-config = %s" % cfg_f.name,
)
self.assertFalse(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBeSetFromAConfigFileByAbbreviation(self):
"""An abbreviated config file key reaches the same arg, so it's rejected too.
argparse resolves an unambiguous abbreviation of a long option, so
rejecting only the exact key would leave the same file overwrite open.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--name", default="world")
self.assertParseArgsRaises(
"write-conf can only be set on the command line",
args=[],
config_file_contents="name = attacker\nwrite-conf = %s" % cfg_f.name,
)
self.assertFalse(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_ConfigFileCantRedirectTheUsersOwnPath(self):
"""A config file must not be able to change where the user asked to write.
Config file args are spliced in after any positional args, so a config
file entry could otherwise win the last-one-wins store and send the
output to a path of its choosing instead of the one the user gave.
"""
users_path = tempfile.NamedTemporaryFile(mode="w+", delete=False)
users_path.close()
os.remove(users_path.name)
victims_path = tempfile.NamedTemporaryFile(mode="w+", delete=False)
victims_path.write("original contents")
victims_path.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--name", default="world")
self.add_arg("rest", nargs="*")
self.assertParseArgsRaises(
"write-config can only be set on the command line",
args=["-w", users_path.name, "--", "extra"],
config_file_contents="write-config = %s" % victims_path.name,
)
with open(victims_path.name) as f:
self.assertEqual(f.read(), "original contents")
self.assertFalse(os.path.exists(users_path.name))
os.remove(victims_path.name)
def testWriteOutConfigFileArg_UnrelatedArgsDontMakeItReachable(self):
"""An unrelated arg that merely looks similar must not enable the write.
The config file is the only thing naming the write-out arg here, so it
must be rejected no matter what else the command line contains.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("-week", action="store_true")
self.add_arg("--name", default="world")
self.assertParseArgsRaises(
"write-config can only be set on the command line",
args=["-week", "--name", "bob"],
config_file_contents="write-config = %s" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBeSetFromAConfigFileValue(self):
"""A config file value must not be able to set it either.
A list value becomes several command line args, so a value can name an
arg just as a key can.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--files", nargs="*")
self.assertParseArgsRaises(
"write-config can only be set on the command line",
args=[],
config_file_contents="files = [--write-config, %s]" % cfg_f.name,
)
self.assertFalse(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBeSetFromAnEnvVarValue(self):
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--files", nargs="*", env_var="FILES")
self.assertParseArgsRaises(
"write-config can only be set on the command line",
args=[],
env_vars={"FILES": json.dumps(["--write-config", cfg_f.name])},
)
self.assertFalse(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBeSetFromAConfigFileValueInAnyForm(self):
"""Every form argparse accepts must be rejected, not just the plain one.
A list value is passed through as command line args verbatim, so it can
carry the option with its value attached, or bundled behind another
short option.
"""
for value_form in ("-w%s", "-vw%s", "--write-config=%s", "--write-conf"):
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("-v", action="store_true")
self.add_arg("--files", nargs="+")
self.assertParseArgsRaises(
"can only be set on the command line",
args=[],
config_file_contents="files = [a, %s]"
% (value_form.replace("%s", cfg_f.name)),
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents", msg=value_form)
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_RejectionCoversEveryFormArgparseAccepts(self):
"""Whatever argparse binds to the write-out arg has to be rejected.
The rejection has to recognize an arg the same way argparse does, so
this asks argparse itself: for each arg string, if a plain
argparse.ArgumentParser with the same options sets the write-out dest
from it, configargparse must refuse to take that arg from a config file.
"""
arg_strings = [
"-w",
"-wPATH",
"-w=PATH",
"-vw",
"-vwPATH",
"-xvw",
"-xvwPATH",
"--write-config",
"--write-config=PATH",
"--write-conf",
"--write",
"--writ",
"--name",
"--nam",
"-v",
"-x",
"-n",
"-nPATH",
"-nw",
"-5",
"--",
"--=PATH",
"--=",
"-=PATH",
"-",
"",
"PATH",
"-write-config",
"-write-config=PATH",
"-write-conf",
"-wr",
"-wr=PATH",
]
for allow_abbrev in (True, False):
for write_out_option_strings in (
["-w", "--write-config"],
["--write-config"],
["-w"],
["-write-config"],
):
parser = configargparse.ArgumentParser(
add_help=False,
allow_abbrev=allow_abbrev,
args_for_writing_out_config_file=write_out_option_strings,
)
reference = argparse.ArgumentParser(
add_help=False, allow_abbrev=allow_abbrev
)
reference.add_argument(
*write_out_option_strings, dest="write_out_config_file_to_this_path"
)
for p in (parser, reference):
p.add_argument("-v", action="store_true")
p.add_argument("-x", action="store_true")
p.add_argument("--write", action="store_true")
p.add_argument("--name")
p.add_argument("-n", dest="nn")
for arg_string in arg_strings:
argparse_sets_it = False
for trailing in ([], ["PATH2"]):
try:
with captured_output():
ns, _ = reference.parse_known_args(
[arg_string] + trailing
)
except SystemExit:
continue
if ns.write_out_config_file_to_this_path is not None:
argparse_sets_it = True
if argparse_sets_it:
with self.subTest(
arg_string=arg_string,
allow_abbrev=allow_abbrev,
write_out=write_out_option_strings,
):
self.assertTrue(
parser._names_a_write_out_config_file_arg(
arg_string, [parser]
)
)
def testWriteOutConfigFileArg_ArgSharingItsPrefixStillWorks(self):
# argparse resolves an exact match straight to that arg, so a config key
# naming a real arg can't reach the write-out one and must be accepted
# even when the write-out arg's name starts with it
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--write", action="store_true")
self.add_arg("--name", default="world")
ns = self.parse(args=[], config_file_contents="write = true\nname = bob")
self.assertTrue(ns.write)
self.assertEqual(ns.name, "bob")
self.assertFalse(self.parser._exit_method_called)
def testWriteOutConfigFileArg_UnknownConfigKeyStillReachesExtras(self):
# a key that only looks like an abbreviation of the write-out arg when
# abbreviations are enabled must stay an ordinary unknown key when they
# aren't, rather than becoming an error
self.initParser(
allow_abbrev=False,
args_for_writing_out_config_file=["-w", "--write-out-config-file"],
)
self.add_arg("--name", default="world")
ns, extras = self.parse_known(args=[], config_file_contents="write = something")
self.assertEqual(ns.name, "world")
self.assertEqual(extras, ["--write=something"])
self.assertFalse(self.parser._exit_method_called)
def testWriteOutConfigFileArg_ConfigFileKeysThatArentStringsStillWork(self):
# YAML maps 'on' to a bool, and ignore_unknown_config_file_keys=True is
# there to tolerate exactly that kind of foreign key
try:
import yaml # noqa: F401
except ImportError:
self.skipTest("PyYAML not installed")
self.initParser(
args_for_writing_out_config_file=["-w", "--write-config"],
config_file_parser_class=configargparse.YAMLConfigFileParser,
ignore_unknown_config_file_keys=True,
)
self.add_arg("--name")
ns = self.parse(args=[], config_file_contents="name: bob\non: something\n")
self.assertEqual(ns.name, "bob")
self.assertFalse(self.parser._exit_method_called)
def testWriteOutConfigFileArg_EmptyConfigValueIsntAnArgsFile(self):
# an empty value isn't a reference to a file of args, even though every
# string starts with one
self.initParser(
args_for_writing_out_config_file=["-w", "--write-config"],
fromfile_prefix_chars="@",
)
self.add_arg("--files", nargs="+")
ns = self.parse(args=[], config_file_contents='files = ["a", ""]')
self.assertEqual(ns.files, ["a", ""])
self.assertFalse(self.parser._exit_method_called)
def testWriteOutConfigFileArg_ConfigValuesThatLookLikeOptionsStillWork(self):
# only a value that actually names the write-out arg is rejected: a
# leading '-' on its own, or a negative number, still parses
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("--dash-value")
self.add_arg("--num", type=int)
ns = self.parse(args=[], config_file_contents="dash-value = -\nnum = -5")
self.assertEqual(ns.dash_value, "-")
self.assertEqual(ns.num, -5)
self.assertFalse(self.parser._exit_method_called)
def testWriteOutConfigFileArg_CantBeSetFromAConfigFileByPrefixAlone(self):
# '--' on its own is argparse's end-of-options separator, but '--=path'
# is an abbreviation that matches every long option
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(
add_help=False, args_for_writing_out_config_file=["-w", "--write-config"]
)
self.add_arg("-n")
self.assertParseArgsRaises(
"can only be set on the command line",
args=[],
config_file_contents="- = %s" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_ConfigFileCantReadArgsFromAFile(self):
"""A config file must not be able to use @file expansion.
argparse expands an @file arg into the args that file contains, and it
does so after the config file's args have been checked, so the file's
contents could name any arg at all.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
args_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
args_f.write("--write-config\n%s\n" % cfg_f.name)
args_f.close()
self.initParser(
args_for_writing_out_config_file=["-w", "--write-config"],
fromfile_prefix_chars="@",
)
self.add_arg("--files", nargs="+")
self.assertParseArgsRaises(
"would read command line args from a file",
args=[],
config_file_contents="files = [a, @%s]" % args_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
# and the same by way of an environment variable
self.initParser(
args_for_writing_out_config_file=["-w", "--write-config"],
fromfile_prefix_chars="@",
)
self.add_arg("--files", nargs="+", env_var="FILES")
self.assertParseArgsRaises(
"would read command line args from a file",
args=[],
env_vars={"FILES": json.dumps(["a", "@" + args_f.name])},
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
os.remove(args_f.name)
def testWriteOutConfigFileArg_AnArgSharingItsDestCantChooseThePath(self):
"""Only the write-out arg itself decides where the config file goes.
Another arg can share its dest and put a value of its own in the
namespace: on the same parser, through parents=, or from a subparser,
which argparse parses into the same namespace. None of them may choose
the path, whether or not the command line asks for a config file.
"""
def sharing_the_dest_on_one_parser():
self.initParser(args_for_writing_out_config_file=["-w"])
self.add_arg("--out", dest="write_out_config_file_to_this_path")
self.add_arg("rest", nargs="*")
return "out", ["--", "extra"]
def sharing_the_dest_through_parents():
base = configargparse.ArgParser(add_help=False)
base.add_argument("-o", "--output")
write_out = configargparse.ArgParser(add_help=False)
write_out.add_argument(
"-w", dest="output", is_write_out_config_file_arg=True
)
self.initParser(parents=[base, write_out])
self.add_arg("rest", nargs="*")
return "output", ["--", "extra"]
victims_path = tempfile.NamedTemporaryFile(mode="w+", delete=False)
victims_path.write("original contents")
victims_path.close()
for build_parser in (
sharing_the_dest_on_one_parser,
sharing_the_dest_through_parents,
):
# the rest of the command line puts the config file's args after the
# write-out arg, which is where a value from one could otherwise win
# the last-one-wins store
config_key, rest_of_command_line = build_parser()
config_file_contents = "%s = %s" % (config_key, victims_path.name)
# with nothing on the command line asking for it, nothing is written
self.parse(
args=rest_of_command_line, config_file_contents=config_file_contents
)
self.assertFalse(self.parser._exit_method_called, msg=config_key)
with open(victims_path.name) as f:
self.assertEqual(f.read(), "original contents", msg=config_key)
# and when it is asked for, it goes where the command line said
users_path = tempfile.NamedTemporaryFile(mode="w+", delete=False)
users_path.close()
os.remove(users_path.name)
build_parser()
self.parse(
args=["-w", users_path.name] + rest_of_command_line,
config_file_contents=config_file_contents,
)
self.assertTrue(self.parser._exit_method_called, msg=config_key)
with open(victims_path.name) as f:
self.assertEqual(f.read(), "original contents", msg=config_key)
self.assertTrue(os.path.exists(users_path.name), msg=config_key)
os.remove(users_path.name)
os.remove(victims_path.name)
def testWriteOutConfigFileArg_ASubparserArgSharingItsDestCantChooseThePath(self):
"""A subcommand parses into the same namespace, and loads its own env vars.
So an arg on a subcommand can share a write-out arg's dest and be set
from the environment without the parent ever seeing it. It still must
not decide where the config file gets written.
"""
victims_path = tempfile.NamedTemporaryFile(mode="w+", delete=False)
victims_path.write("original contents")
victims_path.close()
users_path = tempfile.NamedTemporaryFile(mode="w+", delete=False)
users_path.close()
os.remove(users_path.name)
self.initParser(args_for_writing_out_config_file=["-w"])
self.add_arg("--name", default="world")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser("go").add_argument(
"--out",
dest="write_out_config_file_to_this_path",
env_var="WRITE_OUT_CONFIG_TO",
)
with mock.patch.dict(os.environ, {"WRITE_OUT_CONFIG_TO": victims_path.name}):
self.parse(args=["-w", users_path.name, "go"])
self.assertTrue(self.parser._exit_method_called)
with open(victims_path.name) as f:
self.assertEqual(f.read(), "original contents")
self.assertTrue(os.path.exists(users_path.name))
os.remove(users_path.name)
os.remove(victims_path.name)
def testWriteOutConfigFileArg_ConfigFileCantReadArgsFromASubparsersFile(self):
# the subparser is the one with fromfile_prefix_chars here, and it is
# the one that would expand the arg into whatever the file holds
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
args_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
args_f.write("-w\n%s\n" % cfg_f.name)
args_f.close()
self.initParser()
self.add_arg("--extra", nargs="*")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser(
"go", fromfile_prefix_chars="@", args_for_writing_out_config_file=["-w"]
)
self.assertParseArgsRaises(
"would read command line args from a file",
args=["go", "--"],
config_file_contents="extra = [@%s]" % args_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
os.remove(args_f.name)
def testWriteOutConfigFileArg_CantBeSetFromAConfigFileOnASubparser(self):
"""A subcommand's write-out arg is reachable from the parent's config file.
The parent hands the args it has put together to the subparser, which
treats them as its own command line, so the parent has to check them
against the subcommand's write-out args too.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser()
self.add_arg("--extra", nargs="*")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser(
"go", args_for_writing_out_config_file=["-w", "--write-config"]
)
self.assertParseArgsRaises(
"can only be set on the command line",
args=["go", "--"],
config_file_contents="extra = [-w, %s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_OnASubparserStillWorks(self):
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.close()
self.initParser()
subparsers = self.parser.add_subparsers(dest="cmd")
sub = subparsers.add_parser(
"go", args_for_writing_out_config_file=["-w", "--write-config"]
)
sub.add_argument("--name")
# the subparser is a parser of its own, so it's the one that exits here
with captured_output():
self.assertRaises(
SystemExit, self.parse, ["go", "-w", cfg_f.name, "--name", "bob"]
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_OnASubcommandRestrictsTheWholeParser(self):
"""A write-out arg on any subcommand rules that name out everywhere.
Which subcommand runs can't be told from the args: an option's value
reads exactly like a subcommand name, and the args built from a config
file can name a subcommand themselves. So every subcommand is taken
into account, whatever the command line looks like. The cost is an
error on a key named after a write-out arg on a subcommand that wasn't
going to run, which is the safe direction to be wrong in.
"""
for args in ([], ["deploy"]):
self.initParser()
self.add_arg("--output", env_var="APP_OUTPUT")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser(
"deploy", args_for_writing_out_config_file=["--output-config"]
)
# '--output' is an abbreviation of the subcommand's '--output-config'
self.assertParseArgsRaises(
"can only be set on the command line",
args=args,
config_file_contents="output = /tmp/report.txt",
)
self.assertParseArgsRaises(
"can only be set on the command line",
args=args,
env_vars={"APP_OUTPUT": "/tmp/report.txt"},
)
# a name that doesn't reach it is unaffected
self.initParser()
self.add_arg("--other")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser(
"deploy", args_for_writing_out_config_file=["--output-config"]
)
ns = self.parse(args=[], config_file_contents="other = /tmp/report.txt")
self.assertEqual(ns.other, "/tmp/report.txt")
self.assertFalse(self.parser._exit_method_called)
def testWriteOutConfigFileArg_ArgsFileCharsOnlyMatterWhereTheyCanReachOne(self):
"""An args file only feeds the parser that expands it, and its own subcommands.
So a value naming one is refused when a write-out arg sits at or below
the parser whose args-file character it starts with, and left alone
when it can't reach one.
"""
# the subcommand reads args files, but no write-out arg lives under it
self.initParser(args_for_writing_out_config_file=["-w"])
self.add_arg("--notify", nargs="+")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser("deploy", fromfile_prefix_chars="@")
ns = self.parse(args=[], config_file_contents='notify = ["@oncall", "b"]')
self.assertEqual(ns.notify, ["@oncall", "b"])
self.assertFalse(self.parser._exit_method_called)
# and now one does
self.initParser()
self.add_arg("--notify", nargs="+")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser(
"deploy", fromfile_prefix_chars="@", args_for_writing_out_config_file=["-w"]
)
self.assertParseArgsRaises(
"would read command line args from a file",
args=[],
config_file_contents='notify = ["@oncall", "b"]',
)
def testWriteOutConfigFileArg_CantBeSetWhenAnArgsFileCouldPickTheSubcommand(self):
"""An @file on the command line can name the subcommand itself.
argparse expands it after the config file's args have been checked, so
which subparser will run isn't known yet and every one of them has to
be taken into account.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
args_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
args_f.write("go\n")
args_f.close()
self.initParser(fromfile_prefix_chars="@")
self.add_arg("--write-config")
subparsers = self.parser.add_subparsers(dest="cmd")
subparsers.add_parser("go", args_for_writing_out_config_file=["--write-config"])
self.assertParseArgsRaises(
"can only be set on the command line",
args=["@" + args_f.name],
config_file_contents="write-config = %s" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
os.remove(args_f.name)
def testWriteOutConfigFileArg_CantBeSetOnASubparserBehindAPlainArgparseOne(self):
# a subparser doesn't have to be one of ours to have one of ours under
# it, so the search for write-out args walks through it either way
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser()
self.add_arg("--pair", nargs="+")
outer = self.parser.add_subparsers(
dest="l1", parser_class=argparse.ArgumentParser
).add_parser("outer")
outer.add_subparsers(
dest="l2", parser_class=configargparse.ArgumentParser
).add_parser("inner", args_for_writing_out_config_file=["-w"])
self.assertParseArgsRaises(
"can only be set on the command line",
args=["outer", "inner", "--"],
config_file_contents="pair = [a, b, -w, %s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_SubcommandsAreTakenTogether(self):
"""Once these args can reach a subparser, every subcommand is considered.
Which one will run can't be told from the args alone, since a value
belonging to an earlier option reads exactly like a subcommand name, so
a write-out arg on any of them turns the key down. That costs an error
on a key named after another subcommand's write-out arg, which is the
safe direction to be wrong in.
"""
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
def build():
self.initParser()
self.add_arg("--mode")
subparsers = self.parser.add_subparsers(dest="cmd")
build_parser = subparsers.add_parser("build")
build_parser.add_argument("rest", nargs="*")
subparsers.add_parser(
"run", args_for_writing_out_config_file=["--write-config"]
)
# the value of --mode reads as the name of a subcommand that has no
# write-out arg, while the one that does is the one actually named
build()
self.assertParseArgsRaises(
"can only be set on the command line",
args=["--mode", "build", "run", "--"],
config_file_contents="write-config = %s" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
# and args that stay with the parent are unaffected by any of it
build()
ns = self.parse(args=["--mode", "x", "build"], config_file_contents="mode = y")
self.assertEqual(ns.cmd, "build")
self.assertFalse(self.parser._exit_method_called)
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_AnyPlainStoreActionSpellingWorks(self):
# argparse takes several spellings for the same store action, and all of
# them have to end up recording the path
for action in ("store", None, argparse._StoreAction):
self.initParser()
self.add_arg("-w", is_write_out_config_file_arg=True, action=action)
# a program's own store action keeps whatever it does, and records too
class ExpandUser(argparse._StoreAction):
def __call__(self_inner, parser, namespace, values, option_string=None):
argparse._StoreAction.__call__(
self_inner,
parser,
namespace,
os.path.expanduser(values),
option_string,
)
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.close()
self.initParser()
self.add_arg("-w", is_write_out_config_file_arg=True, action=ExpandUser)
self.add_arg("--name")
self.parse(["-w", cfg_f.name, "--name", "bob"])
self.assertTrue(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_EmptyPathIsStillReported(self):
# an empty path is a path the user asked for, so it fails the way any
# other unwritable path does rather than being quietly skipped
self.initParser(args_for_writing_out_config_file=["-w"])
self.add_arg("--name")
self.assertRaisesRegex(
ValueError,
"Couldn't open for writing",
self.parse,
["--name", "bob", "-w", ""],
)
def testWriteOutConfigFileArg_OnASubcommandReachedByACustomDispatcher(self):
"""A program can register its own subcommand dispatcher.
It won't be an argparse._SubParsersAction, so the search for write-out
args recognizes the shape as well: subcommand names mapped to parsers,
taking the rest of the args.
"""
class CustomParsers(argparse.Action):
def __init__(
self_inner,
option_strings,
prog=None,
parser_class=None,
dest=argparse.SUPPRESS,
required=False,
help=None,
metavar=None,
):
self_inner._name_parser_map = {}
argparse.Action.__init__(
self_inner,
option_strings=option_strings,
dest=dest,
nargs=argparse.PARSER,
choices=self_inner._name_parser_map,
required=required,
help=help,
metavar=metavar,
)
self_inner._parser_class = parser_class
def add_parser(self_inner, name, **kwargs):
parser = self_inner._parser_class(**kwargs)
self_inner._name_parser_map[name] = parser
return parser
def __call__(self_inner, parser, namespace, values, option_string=None):
self_inner._name_parser_map[values[0]].parse_known_args(
values[1:], namespace
)
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser()
self.parser.register("action", "parsers", CustomParsers)
self.add_arg("--pair", nargs="+")
self.parser.add_subparsers(
dest="cmd", parser_class=configargparse.ArgumentParser
).add_parser("deploy", args_for_writing_out_config_file=["-w"])
self.assertEqual(len(self.parser._reachable_parsers()), 2)
self.assertParseArgsRaises(
"can only be set on the command line",
args=["deploy", "--"],
config_file_contents="pair = [x, -w, %s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBeSetFromAConfigFileByPrefixCharAlone(self):
# argparse looks a single-prefix-char arg up by the part before any '=',
# and takes any option starting with it, so a lone '-' reaches a short
# option when it is the only candidate
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(
prefix_chars="+-", add_help=False, args_for_writing_out_config_file=["-w"]
)
self.add_arg("++files", nargs="+")
self.assertParseArgsRaises(
"can only be set on the command line",
args=[],
config_file_contents="files = [a, -=%s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_UsesThePathTheActionStored(self):
"""A store action of the program's own may change the path on its way in.
The file has to be written where the action put it, not where the raw
arg pointed.
"""
class Prefixer(argparse._StoreAction):
def __call__(self_inner, parser, namespace, values, option_string=None):
argparse._StoreAction.__call__(
self_inner, parser, namespace, values + ".ini", option_string
)
cfg_f = tempfile.NamedTemporaryFile(mode="w+", suffix=".ini", delete=False)
cfg_f.close()
self.initParser()
self.add_arg("-w", is_write_out_config_file_arg=True, action=Prefixer)
self.add_arg("--name", default="bob")
self.parse(["-w", cfg_f.name[: -len(".ini")]])
self.assertTrue(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_StoreActionRegisteredUnderAName(self):
# a store action reached through the registry is wrapped like any other
class MyStore(argparse._StoreAction):
pass
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.close()
self.initParser()
self.parser.register("action", "mystore", MyStore)
self.add_arg("-w", is_write_out_config_file_arg=True, action="mystore")
self.add_arg("--name", default="bob")
self.parse(["-w", cfg_f.name])
self.assertTrue(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBeSetByAFlagWithMoreOptionsAfterIt(self):
# before Python 3.11 argparse reads whatever follows the '=' of a
# single-dash flag that takes no value as more short options, so '-v=w'
# reaches '-w' there
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("-v", action="store_true")
self.add_arg("--files", nargs="+")
self.assertParseArgsRaises(
"can only be set on the command line",
args=[],
config_file_contents="files = [a, -v=w, %s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_RejectionDoesntRelyOnErrorStopping(self):
"""error() is meant to stop the program, but a program can override exit().
The args are dropped rather than added when one of them names a
write-out arg, so the protection holds either way.
"""
class KeepsGoing(configargparse.ArgumentParser):
def exit(self_inner, status=0, message=None):
pass
def error(self_inner, message):
self_inner.exit(2, message)
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
parser = KeepsGoing(args_for_writing_out_config_file=["-w", "--write-config"])
parser.add_argument("--files", nargs="*")
with captured_output():
parser.parse_known_args(
args=[],
config_file_contents="files = [--write-config, %s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testSubcommandsDispatchedByAPlainChoicesDictStillParse(self):
# an ordinary program can dispatch its own subcommands with a dict of
# choices that holds anything at all, and it has no write-out arg
def handler():
pass
self.initParser()
self.add_arg("--verbose", action="store_true")
self.add_arg("command", nargs=argparse.PARSER, choices={"run": handler})
# the dict values aren't parsers, and looking for write-out args must
# not trip over them. Behaviour is otherwise exactly as it was before:
# a PARSER positional swallows the args added from the config file.
ns = self.parse(["run", "x"], config_file_contents="verbose = true")
self.assertFalse(ns.verbose)
self.assertEqual(ns.command, ["run", "x", "--verbose"])
self.initParser()
self.add_arg("--verbose", action="store_true")
self.add_arg("command", nargs=argparse.PARSER, choices={"run": handler})
ns = self.parse(["run", "x"])
self.assertEqual(ns.command, ["run", "x"])
def testWriteOutConfigFileArg_CantBeSetAfterAMultiLetterFlagAndAnEquals(self):
# before Python 3.11.9 and 3.12.3, argparse reads what follows the '='
# of a single-dash flag that takes no value as more short options, so
# '-force=w' reaches '-w' there
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("-force", action="store_true")
self.add_arg("--files", nargs="+")
self.assertParseArgsRaises(
"can only be set on the command line",
args=[],
config_file_contents="files = [a, -force=w, %s]" % cfg_f.name,
)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_ActionBuiltByACallable(self):
# argparse takes any callable that returns an action, not just a class
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.close()
self.initParser(add_help=False)
self.add_arg(
"-w",
action=functools.partial(argparse._StoreAction),
is_write_out_config_file_arg=True,
)
self.add_arg("--name", default="bob")
self.parse(["-w", cfg_f.name])
self.assertTrue(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_PathIsForgottenBetweenParses(self):
"""A path from one parse must not still be there for the next one.
Uses a parser whose exit() doesn't stop, so parsing carries on past the
first write the way a program overriding exit() would.
"""
class KeepsGoing(configargparse.ArgumentParser):
def exit(self_inner, status=0, message=None):
pass
first = tempfile.NamedTemporaryFile(mode="w+", delete=False)
first.close()
os.remove(first.name)
second = tempfile.NamedTemporaryFile(mode="w+", delete=False)
second.close()
os.remove(second.name)
parser = KeepsGoing(args_for_writing_out_config_file=["-w"])
parser.add_argument("--name", default="bob")
with captured_output():
parser.parse_known_args(["-w", first.name])
self.assertTrue(os.path.exists(first.name))
os.remove(first.name)
# the second parse doesn't ask for one, so nothing is written
with captured_output():
parser.parse_known_args([])
self.assertFalse(os.path.exists(first.name))
self.assertFalse(os.path.exists(second.name))
def testWriteOutConfigFileArg_CantHaveAnEnvVar(self):
# an env var that sets one would overwrite the path it names, so the
# combination is rejected up front rather than at parse time
self.initParser()
self.assertRaisesRegex(
ValueError,
"is_write_out_config_file_arg=True can't also have env_var set",
self.add_arg,
"--write-config",
is_write_out_config_file_arg=True,
env_var="WRITE_CONFIG",
)
def testWriteOutConfigFileArg_IgnoreUnknownConfigFileKeys(self):
# ignore_unknown_config_file_keys=True discards the key like any other
# unknown one, so it neither writes the file nor errors
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(
args_for_writing_out_config_file=["-w", "--write-config"],
ignore_unknown_config_file_keys=True,
)
self.add_arg("--name", default="world")
ns = self.parse(args=[], config_file_contents="write-config = %s" % cfg_f.name)
self.assertEqual(ns.name, "world")
self.assertFalse(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CommandLineFormsAllStillWork(self):
"""Every form of the arg that argparse accepts must still write the file."""
for command_line_args in (
["--write-config", "%s"], # long form
["--write-config=%s"], # long form with the value attached
["--write-conf", "%s"], # unambiguous abbreviation
["-w", "%s"], # short form
["-w%s"], # short form with the value attached
["-vw", "%s"], # bundled with another short option
["-vw%s"], # bundled, with the value attached
):
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.close()
self.initParser(args_for_writing_out_config_file=["-w", "--write-config"])
self.add_arg("-v", action="store_true")
self.add_arg("--name")
self.parse(
[a.replace("%s", cfg_f.name) for a in command_line_args]
+ ["--name", "bob"]
)
self.assertTrue(self.parser._exit_method_called, msg=str(command_line_args))
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n", msg=str(command_line_args))
os.remove(cfg_f.name)
def testWriteOutConfigFileArg_CantBePositional(self):
"""A positional can't be one of these.
A config file value becomes a plain command line arg, and a positional
would take one of those just as readily as one the user typed. Telling
them apart would mean working out how argparse hands out positionals
over a whole arg list, so the combination is turned down instead.
"""
self.initParser()
self.assertRaisesRegex(
ValueError,
"is_write_out_config_file_arg=True can't be a positional arg",
self.add_arg,
"outpath",
nargs="?",
is_write_out_config_file_arg=True,
)
def testWriteOutConfigFileArg_FromfilePrefixChars(self):
# argparse expands @file args into the command line, so an arg supplied
# that way is still a command line arg
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.close()
args_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
args_f.write("--write-config\n%s\n" % cfg_f.name)
args_f.close()
self.initParser(
args_for_writing_out_config_file=["-w", "--write-config"],
fromfile_prefix_chars="@",
)
self.add_arg("--name")
self.parse(["@" + args_f.name, "--name", "bob"])
self.assertTrue(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "name = bob\n")
os.remove(cfg_f.name)
os.remove(args_f.name)
def testWriteOutConfigFileArg_OutputFileIsntTruncatedOnFailure(self):
"""Nothing is opened for writing until the contents to write exist."""
class FailingConfigFileParser(configargparse.DefaultConfigFileParser):
def serialize(self_inner, items):
raise ValueError("can't serialize that")
cfg_f = tempfile.NamedTemporaryFile(mode="w+", delete=False)
cfg_f.write("original contents")
cfg_f.close()
self.initParser(
args_for_writing_out_config_file=["-w"],
config_file_parser_class=FailingConfigFileParser,
)
self.add_arg("--name")
self.assertRaises(
ValueError, self.parse, args=["-w", cfg_f.name, "--name", "bob"]
)
self.assertFalse(self.parser._exit_method_called)
with open(cfg_f.name) as f:
self.assertEqual(f.read(), "original contents")
os.remove(cfg_f.name)
def testMethodAliases(self):
p = self.parser
p.add("-a", "--arg-a", default=3)
p.add_arg("-b", "--arg-b", required=True)
p.add_argument("-c")
g1 = p.add_argument_group(title="group1", description="descr")
g1.add("-d", "--arg-d", required=True)
g1.add_arg("-e", "--arg-e", required=True)
g1.add_argument("-f", "--arg-f", default=5)
g2 = p.add_mutually_exclusive_group(required=True)
g2.add("-x", "--arg-x")
g2.add_arg("-y", "--arg-y")
g2.add_argument("-z", "--arg-z", default=5)
# verify that flags must be globally unique
g2 = p.add_argument_group(title="group2", description="descr")
self.assertRaises(argparse.ArgumentError, g1.add, "-c")
self.assertRaises(argparse.ArgumentError, g2.add, "-f")
self.initParser()
p = self.parser
options = p.parse(args=[])
self.assertDictEqual(vars(options), {})
def testConfigOpenFuncError(self):
# test OSError -- str(OSError(errno, strerror)) formats as
# "[Errno N] strerror", so the full message is preserved.
def error_func(path):
raise OSError(9, "some error")
self.initParser(config_file_open_func=error_func)
self.parser.add_argument("-g", is_config_file=True)
self.assertParseArgsRaises(
r"Unable to open config file: file\.txt\. Error: \[Errno 9\] some error",
args="-g file.txt",
)
# test other error
def error_func(path):
raise Exception("custom error")
self.initParser(config_file_open_func=error_func)
self.parser.add_argument("-g", is_config_file=True)
self.assertParseArgsRaises(
"Unable to open config file: file.txt. Error: custom error",
args="-g file.txt",
)
# test custom 2-arg exception -- both args must be preserved (X5
# regression: the previous len(e.args) == 2 OSError shortcut would
# silently drop the first arg).
class CustomTwoArgError(Exception):
pass
def error_func(path):
raise CustomTwoArgError("CODE", "human message")
self.initParser(config_file_open_func=error_func)
self.parser.add_argument("-g", is_config_file=True)
self.assertParseArgsRaises(
r"Unable to open config file: file\.txt\. Error: \('CODE', 'human message'\)",
args="-g file.txt",
)
def testDoubleDashSeparator(self):
"""Test that -- separator correctly separates optional from positional args
when config file or env vars are used. Regression test for issue #298."""
config_file = tempfile.NamedTemporaryFile(
mode="w", delete=False, suffix=".conf"
)
config_file.write("list = [1, 2, 3]\n")
config_file.flush()
config_file.close()
try:
# Test with config file and -- separator
self.initParser(args_for_setting_config_path=["-c", "--config"])
self.parser.add_argument("--list", action="append")
self.parser.add_argument("positional_arg", nargs="*")
ns = self.parse(args="-c %s -- foo bar" % config_file.name)
self.assertEqual(ns.positional_arg, ["foo", "bar"])
self.assertEqual(ns.list, ["1", "2", "3"])
# Test without -- separator
ns = self.parse(args="-c %s foo bar" % config_file.name)
self.assertEqual(ns.positional_arg, ["foo", "bar"])
self.assertEqual(ns.list, ["1", "2", "3"])
# Test with env var and -- separator
self.initParser()
self.parser.add_argument("--list", action="append", env_var="MY_LIST")
self.parser.add_argument("positional_arg", nargs="*")
old_env = os.environ.get("MY_LIST")
try:
os.environ["MY_LIST"] = "[1,2,3]"
ns = self.parse(args="-- foo bar")
self.assertEqual(ns.positional_arg, ["foo", "bar"])
self.assertEqual(ns.list, ["1", "2", "3"])
finally:
if old_env is not None:
os.environ["MY_LIST"] = old_env
elif "MY_LIST" in os.environ:
del os.environ["MY_LIST"]
finally:
os.unlink(config_file.name)
def testRemainderWithConfigFile(self):
"""Test that nargs=REMAINDER works correctly with config files.
Regression test for issue #285."""
config_file = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".cfg")
config_file.write("config_file_option=value_from_config\n")
config_file.flush()
config_file.close()
try:
self.initParser()
self.parser.add_argument(
"--config", is_config_file=True, default=config_file.name
)
self.parser.add_argument("--config_file_option", nargs="*", default=None)
self.parser.add_argument(
"remainder_option", nargs=argparse.REMAINDER, default=None
)
ns = self.parse(args=["test"])
self.assertEqual(ns.remainder_option, ["test"])
self.assertEqual(ns.config_file_option, ["value_from_config"])
ns = self.parse(args=["test", "arg1", "arg2"])
self.assertEqual(ns.remainder_option, ["test", "arg1", "arg2"])
self.assertEqual(ns.config_file_option, ["value_from_config"])
finally:
os.unlink(config_file.name)
def testEmptyValuesIgnored(self):
"""Test that empty string values from config files and env vars are ignored
for args with nargs. Regression test for issue #296."""
# Test empty value in config file
config_file = tempfile.NamedTemporaryFile(
mode="w", delete=False, suffix=".conf"
)
config_file.write("test-opt=\n")
config_file.flush()
config_file.close()
try:
self.initParser()
self.parser.add_argument(
"--config", is_config_file=True, default=config_file.name
)
self.parser.add_argument(
"--test-opt", nargs=2, default=["default1", "default2"]
)
ns = self.parse(args=[])
self.assertEqual(ns.test_opt, ["default1", "default2"])
finally:
os.unlink(config_file.name)
# Test empty environment variable
self.initParser()
self.parser.add_argument(
"--test-opt", nargs=2, env_var="TEST_OPT", default=["default1", "default2"]
)
old_env = os.environ.get("TEST_OPT")
try:
os.environ["TEST_OPT"] = ""
ns = self.parse(args=[])
self.assertEqual(ns.test_opt, ["default1", "default2"])
finally:
if old_env is not None:
os.environ["TEST_OPT"] = old_env
elif "TEST_OPT" in os.environ:
del os.environ["TEST_OPT"]
def testConfigArgOrderWithOptsOnCli(self):
"""Test that config args with nargs/append are parsed correctly when
optional args are already on the command line."""
config_file = tempfile.NamedTemporaryFile(
mode="w", delete=False, suffix=".conf"
)
config_file.write("from_config = [x, y]\n")
config_file.flush()
config_file.close()
try:
self.initParser()
self.parser.add_argument(
"--config", is_config_file=True, default=config_file.name
)
self.parser.add_argument("--from_config", action="append")
self.parser.add_argument("--cli_opt")
self.parser.add_argument("positional", nargs="*")
ns = self.parse(args="--cli_opt val pos1 pos2")
self.assertEqual(ns.positional, ["pos1", "pos2"])
self.assertEqual(ns.cli_opt, "val")
self.assertEqual(ns.from_config, ["x", "y"])
finally:
os.unlink(config_file.name)
def testConfigArgOrderNoOptsOnCli(self):
"""Test that config args are parsed correctly when no optional args
are on the command line (only positional args)."""
config_file = tempfile.NamedTemporaryFile(
mode="w", delete=False, suffix=".conf"
)
config_file.write("flag\n")
config_file.flush()
config_file.close()
try:
self.initParser()
self.parser.add_argument(
"--config", is_config_file=True, default=config_file.name
)
self.parser.add_argument("--flag", action="store_true")
self.parser.add_argument("positional")
ns = self.parse(args="mypos")
self.assertEqual(ns.positional, "mypos")
self.assertTrue(ns.flag)
finally:
os.unlink(config_file.name)
def testEnvVarArgOrderWithOptsOnCli(self):
"""Test that env var args with nargs/append are parsed correctly when
optional args are already on the command line."""
self.initParser()
self.parser.add_argument("--from_env", action="append", env_var="FROM_ENV")
self.parser.add_argument("--cli_opt")
self.parser.add_argument("positional", nargs="*")
old_env = os.environ.get("FROM_ENV")
try:
os.environ["FROM_ENV"] = "[a,b]"
ns = self.parse(args="--cli_opt val pos1 pos2")
self.assertEqual(ns.positional, ["pos1", "pos2"])
self.assertEqual(ns.cli_opt, "val")
self.assertEqual(ns.from_env, ["a", "b"])
finally:
if old_env is not None:
os.environ["FROM_ENV"] = old_env
elif "FROM_ENV" in os.environ:
del os.environ["FROM_ENV"]
def testEnvVarArgOrderNoOptsOnCli(self):
"""Test that env var args are parsed correctly when no optional args
are on the command line (only positional args)."""
self.initParser()
self.parser.add_argument("--flag", action="store_true", env_var="MY_FLAG")
self.parser.add_argument("positional")
old_env = os.environ.get("MY_FLAG")
try:
os.environ["MY_FLAG"] = "true"
ns = self.parse(args="mypos")
self.assertEqual(ns.positional, "mypos")
self.assertTrue(ns.flag)
finally:
if old_env is not None:
os.environ["MY_FLAG"] = old_env
elif "MY_FLAG" in os.environ:
del os.environ["MY_FLAG"]
class TestConfigFileParsers(TestCase):
"""Test ConfigFileParser subclasses in isolation"""
def testDefaultConfigFileParser_Basic(self):
p = configargparse.DefaultConfigFileParser()
self.assertGreater(len(p.get_syntax_description()), 0)
# test the simplest case
input_config_str = StringIO("""a: 3\n""")
parsed_obj = p.parse(input_config_str)
output_config_str = p.serialize(parsed_obj)
self.assertEqual(
input_config_str.getvalue().replace(": ", " = "), output_config_str
)
self.assertDictEqual(parsed_obj, {"a": "3"})
def testDefaultConfigFileParser_SerializeRendersValuesAsBefore(self):
# the newline check must not change how a value that isn't a plain
# string comes out: str() and format() differ for an Enum before 3.11
from enum import Enum, IntEnum
class Color(str, Enum):
RED = "red"
class Level(IntEnum):
HIGH = 2
p = configargparse.DefaultConfigFileParser()
self.assertEqual(
p.serialize(OrderedDict([("color", Color.RED), ("level", Level.HIGH)])),
"color = {}\nlevel = {}\n".format(Color.RED, Level.HIGH),
)
def testDefaultConfigFileParser_SerializeRejectsNewlines(self):
# this format puts one key per line, so a newline in a value would come
# back as extra keys rather than as part of the value
p = configargparse.DefaultConfigFileParser()
self.assertRaisesRegex(
ValueError,
"can't contain newlines",
p.serialize,
OrderedDict([("a", "3\nb = 4")]),
)
self.assertRaisesRegex(
ValueError,
"can't contain newlines",
p.serialize,
OrderedDict([("a", ["3", "4\nb = 5"])]),
)
self.assertRaisesRegex(
ValueError,
"can't contain newlines",
p.serialize,
OrderedDict([("a\nb", "3")]),
)
def testDefaultConfigFileParser_All(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
"# comment1 ",
"[ some section ]",
"----",
"---------",
"_a: 3",
"; comment2 ",
"_b = c",
"_list_arg1 = [a, b, c]",
"_str_arg = true",
"_list_arg2 = [1, 2, 3]",
]
# test parse
input_config_str = StringIO("\n".join(config_lines) + "\n")
parsed_obj = p.parse(input_config_str)
# test serialize
output_config_str = p.serialize(parsed_obj)
self.assertEqual(
"\n".join(l.replace(": ", " = ") for l in config_lines if l.startswith("_"))
+ "\n",
output_config_str,
)
self.assertDictEqual(
parsed_obj,
{
"_a": "3",
"_b": "c",
"_list_arg1": ["a", "b", "c"],
"_str_arg": "true",
"_list_arg2": [1, 2, 3],
},
)
self.assertListEqual(parsed_obj["_list_arg1"], ["a", "b", "c"])
self.assertListEqual(parsed_obj["_list_arg2"], [1, 2, 3])
def testDefaultConfigFileParser_BasicValues(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{
"line": "key = value # comment # comment",
"expected": ("key", "value", "comment # comment"),
},
{"line": "key=value#comment ", "expected": ("key", "value#comment", None)},
{"line": "key=value", "expected": ("key", "value", None)},
{"line": "key =value", "expected": ("key", "value", None)},
{"line": "key= value", "expected": ("key", "value", None)},
{"line": "key = value", "expected": ("key", "value", None)},
{"line": "key = value", "expected": ("key", "value", None)},
{"line": " key = value ", "expected": ("key", "value", None)},
{"line": "key:value", "expected": ("key", "value", None)},
{"line": "key :value", "expected": ("key", "value", None)},
{"line": "key: value", "expected": ("key", "value", None)},
{"line": "key : value", "expected": ("key", "value", None)},
{"line": "key : value", "expected": ("key", "value", None)},
{"line": " key : value ", "expected": ("key", "value", None)},
{"line": "key value", "expected": ("key", "value", None)},
{"line": "key value", "expected": ("key", "value", None)},
{"line": " key value ", "expected": ("key", "value", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_QuotedValues(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{"line": 'key="value"', "expected": ("key", "value", None)},
{"line": 'key = "value"', "expected": ("key", "value", None)},
{"line": ' key = "value" ', "expected": ("key", "value", None)},
{"line": 'key=" value "', "expected": ("key", " value ", None)},
{"line": 'key = " value "', "expected": ("key", " value ", None)},
{"line": ' key = " value " ', "expected": ("key", " value ", None)},
{"line": "key='value'", "expected": ("key", "value", None)},
{"line": "key = 'value'", "expected": ("key", "value", None)},
{"line": " key = 'value' ", "expected": ("key", "value", None)},
{"line": "key=' value '", "expected": ("key", " value ", None)},
{"line": "key = ' value '", "expected": ("key", " value ", None)},
{"line": " key = ' value ' ", "expected": ("key", " value ", None)},
{"line": 'key="', "expected": ("key", '"', None)},
{"line": 'key = "', "expected": ("key", '"', None)},
{"line": ' key = " ', "expected": ("key", '"', None)},
{"line": "key = '\"value\"'", "expected": ("key", '"value"', None)},
{"line": "key = \"'value'\"", "expected": ("key", "'value'", None)},
{"line": 'key = ""value""', "expected": ("key", '"value"', None)},
{"line": "key = ''value''", "expected": ("key", "'value'", None)},
{"line": 'key="value', "expected": ("key", '"value', None)},
{"line": 'key = "value', "expected": ("key", '"value', None)},
{"line": ' key = "value ', "expected": ("key", '"value', None)},
{"line": 'key=value"', "expected": ("key", 'value"', None)},
{"line": 'key = value"', "expected": ("key", 'value"', None)},
{"line": ' key = value " ', "expected": ("key", 'value "', None)},
{"line": "key='value", "expected": ("key", "'value", None)},
{"line": "key = 'value", "expected": ("key", "'value", None)},
{"line": " key = 'value ", "expected": ("key", "'value", None)},
{"line": "key=value'", "expected": ("key", "value'", None)},
{"line": "key = value'", "expected": ("key", "value'", None)},
{"line": " key = value ' ", "expected": ("key", "value '", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_BlankValues(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{"line": "key=", "expected": ("key", "", None)},
{"line": "key =", "expected": ("key", "", None)},
{"line": "key= ", "expected": ("key", "", None)},
{"line": "key = ", "expected": ("key", "", None)},
{"line": "key = ", "expected": ("key", "", None)},
{"line": " key = ", "expected": ("key", "", None)},
{"line": "key:", "expected": ("key", "", None)},
{"line": "key :", "expected": ("key", "", None)},
{"line": "key: ", "expected": ("key", "", None)},
{"line": "key : ", "expected": ("key", "", None)},
{"line": "key : ", "expected": ("key", "", None)},
{"line": " key : ", "expected": ("key", "", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_UnspecifiedValues(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{"line": "key ", "expected": ("key", "true", None)},
{"line": "key", "expected": ("key", "true", None)},
{"line": "key ", "expected": ("key", "true", None)},
{"line": " key ", "expected": ("key", "true", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_ColonEqualSignValue(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{"line": "key=:", "expected": ("key", ":", None)},
{"line": "key =:", "expected": ("key", ":", None)},
{"line": "key= :", "expected": ("key", ":", None)},
{"line": "key = :", "expected": ("key", ":", None)},
{"line": "key = :", "expected": ("key", ":", None)},
{"line": " key = : ", "expected": ("key", ":", None)},
{"line": "key:=", "expected": ("key", "=", None)},
{"line": "key :=", "expected": ("key", "=", None)},
{"line": "key: =", "expected": ("key", "=", None)},
{"line": "key : =", "expected": ("key", "=", None)},
{"line": "key : =", "expected": ("key", "=", None)},
{"line": " key : = ", "expected": ("key", "=", None)},
{"line": "key==", "expected": ("key", "=", None)},
{"line": "key ==", "expected": ("key", "=", None)},
{"line": "key= =", "expected": ("key", "=", None)},
{"line": "key = =", "expected": ("key", "=", None)},
{"line": "key = =", "expected": ("key", "=", None)},
{"line": " key = = ", "expected": ("key", "=", None)},
{"line": "key::", "expected": ("key", ":", None)},
{"line": "key ::", "expected": ("key", ":", None)},
{"line": "key: :", "expected": ("key", ":", None)},
{"line": "key : :", "expected": ("key", ":", None)},
{"line": "key : :", "expected": ("key", ":", None)},
{"line": " key : : ", "expected": ("key", ":", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_ValuesWithComments(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{"line": "key=value#comment ", "expected": ("key", "value#comment", None)},
{"line": "key=value #comment", "expected": ("key", "value", "comment")},
{
"line": " key = value # comment",
"expected": ("key", "value", "comment"),
},
{"line": "key:value#comment", "expected": ("key", "value#comment", None)},
{"line": "key:value #comment", "expected": ("key", "value", "comment")},
{
"line": " key : value # comment",
"expected": ("key", "value", "comment"),
},
{"line": "key=value;comment ", "expected": ("key", "value;comment", None)},
{"line": "key=value ;comment", "expected": ("key", "value", "comment")},
{
"line": " key = value ; comment",
"expected": ("key", "value", "comment"),
},
{"line": "key:value;comment", "expected": ("key", "value;comment", None)},
{"line": "key:value ;comment", "expected": ("key", "value", "comment")},
{
"line": " key : value ; comment",
"expected": ("key", "value", "comment"),
},
{
"line": "key = value # comment # comment",
"expected": ("key", "value", "comment # comment"),
},
{
"line": 'key = "value # comment" # comment',
"expected": ("key", "value # comment", "comment"),
},
{"line": 'key = "#" ; comment', "expected": ("key", "#", "comment")},
{"line": 'key = ";" # comment', "expected": ("key", ";", "comment")},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_NegativeValues(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{"line": "key = -10", "expected": ("key", "-10", None)},
{"line": "key : -10", "expected": ("key", "-10", None)},
{"line": "key -10", "expected": ("key", "-10", None)},
{"line": 'key = "-10"', "expected": ("key", "-10", None)},
{"line": "key = '-10'", "expected": ("key", "-10", None)},
{"line": "key=-10", "expected": ("key", "-10", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testDefaultConfigFileParser_KeySyntax(self):
p = configargparse.DefaultConfigFileParser()
# test the all syntax case
config_lines = [
{
"line": "key_underscore = value",
"expected": ("key_underscore", "value", None),
},
{"line": "key_underscore=", "expected": ("key_underscore", "", None)},
{"line": "key_underscore", "expected": ("key_underscore", "true", None)},
{
"line": "_key_underscore = value",
"expected": ("_key_underscore", "value", None),
},
{"line": "_key_underscore=", "expected": ("_key_underscore", "", None)},
{"line": "_key_underscore", "expected": ("_key_underscore", "true", None)},
{
"line": "key_underscore_ = value",
"expected": ("key_underscore_", "value", None),
},
{"line": "key_underscore_=", "expected": ("key_underscore_", "", None)},
{"line": "key_underscore_", "expected": ("key_underscore_", "true", None)},
{"line": "key-dash = value", "expected": ("key-dash", "value", None)},
{"line": "key-dash=", "expected": ("key-dash", "", None)},
{"line": "key-dash", "expected": ("key-dash", "true", None)},
{"line": "key@word = value", "expected": ("key@word", "value", None)},
{"line": "key@word=", "expected": ("key@word", "", None)},
{"line": "key@word", "expected": ("key@word", "true", None)},
{"line": "key$word = value", "expected": ("key$word", "value", None)},
{"line": "key$word=", "expected": ("key$word", "", None)},
{"line": "key$word", "expected": ("key$word", "true", None)},
{"line": "key.word = value", "expected": ("key.word", "value", None)},
{"line": "key.word=", "expected": ("key.word", "", None)},
{"line": "key.word", "expected": ("key.word", "true", None)},
]
for test in config_lines:
with self.subTest(test=test):
parsed_obj = p.parse(StringIO(test["line"]))
parsed_obj = dict(parsed_obj)
expected = {test["expected"][0]: test["expected"][1]}
self.assertDictEqual(
parsed_obj, expected, msg="Line %r" % (test["line"])
)
def testYAMLConfigFileParser_Basic(self):
try:
import yaml
except:
logging.warning(
"WARNING: PyYAML not installed. Couldn't test YAMLConfigFileParser"
)
return
p = configargparse.YAMLConfigFileParser()
self.assertGreater(len(p.get_syntax_description()), 0)
input_config_str = StringIO("""a: '3'\n""")
parsed_obj = p.parse(input_config_str)
output_config_str = p.serialize(dict(parsed_obj))
self.assertEqual(input_config_str.getvalue(), output_config_str)
self.assertDictEqual(parsed_obj, {"a": "3"})
def testYAMLConfigFileParser_All(self):
try:
import yaml
except:
logging.warning(
"WARNING: PyYAML not installed. Couldn't test YAMLConfigFileParser"
)
return
p = configargparse.YAMLConfigFileParser()
# test the all syntax case
config_lines = [
"a: '3'",
"list_arg:",
"- 1",
"- 2",
"- 3",
]
# test parse
input_config_str = StringIO("\n".join(config_lines) + "\n")
parsed_obj = p.parse(input_config_str)
# test serialize
output_config_str = p.serialize(parsed_obj)
self.assertEqual(input_config_str.getvalue(), output_config_str)
self.assertDictEqual(parsed_obj, {"a": "3", "list_arg": [1, 2, 3]})
def testYAMLConfigFileParser_w_ArgumentParser_parsed_values(self):
try:
import yaml
except:
raise AssertionError(
"WARNING: PyYAML not installed. Couldn't test YAMLConfigFileParser"
)
return
parser = configargparse.ArgumentParser(
config_file_parser_class=configargparse.YAMLConfigFileParser
)
parser.add_argument("-c", "--config", is_config_file=True)
parser.add_argument("--verbosity", action="count")
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--level", type=int)
config_lines = ["verbosity: 3", "verbose: true", "level: 35"]
config_str = "\n".join(config_lines) + "\n"
config_file = tempfile.gettempdir() + "/temp_YAMLConfigFileParser.cfg"
with open(config_file, "w") as f:
f.write(config_str)
args = parser.parse_args(["--config=%s" % config_file])
assert args.verbosity == 3
assert args.verbose == True
assert args.level == 35
class TestTomlConfigParser(unittest.TestCase):
def write_toml_file(self, content, obj=StringIO):
f = obj()
dedent = lambda x: x
if isinstance(content, str):
dedent = textwrap.dedent
f.write(dedent(content))
f.seek(0)
return f
def test_section(self):
f = self.write_toml_file("""
[section]
key1 = 'toml1'
key2 = 'toml2'
""")
parser = configargparse.TomlConfigParser(["section"])
self.assertEqual(parser.parse(f), {"key1": "toml1", "key2": "toml2"})
def test_no_sections(self):
f = self.write_toml_file("""
[section]
key1 = 'toml1'
key2 = 'toml2'
""")
parser = configargparse.TomlConfigParser([])
self.assertEqual(parser.parse(f), {})
def test_empty_section(self):
f = self.write_toml_file("[section]")
parser = configargparse.TomlConfigParser(["section"])
self.assertEqual(parser.parse(f), {})
def test_empty_file(self):
f = self.write_toml_file("")
parser = configargparse.TomlConfigParser(["section"])
self.assertEqual(parser.parse(f), {})
@unittest.expectedFailure # Ints should be strings
def test_advanced(self):
f = self.write_toml_file("""
[tool.section]
key1 = "toml1"
key2 = [1, 2, 3]
""")
parser = configargparse.TomlConfigParser(["tool.section"])
self.assertEqual(parser.parse(f), {"key1": "toml1", "key2": ["1", "2", "3"]})
def test_read_without_toml_packages(self):
f = self.write_toml_file("""
[tool.section]
key1 = "toml1"
key2 = [1, 2, 3]
""")
parser = configargparse.TomlConfigParser(["tool.section"])
with mock.patch.dict(sys.modules, {"toml": None, "tomllib": None}):
with self.assertRaises(configargparse.ConfigFileParserMissingDependency):
parser.parse(f)
def test_binary_read_works(self):
# Binary mode now works with tomllib (Python 3.11+)
f = self.write_toml_file(
b"""[tool.section]\nkey1 = "toml1"
""",
obj=BytesIO,
)
parser = configargparse.TomlConfigParser(["tool.section"])
# Should successfully parse binary stream
self.assertEqual(parser.parse(f), {"key1": "toml1"})
def test_serialize_with_section(self):
parser = configargparse.TomlConfigParser(["section"])
try:
import toml
except ImportError:
self.skipTest("toml package not installed")
items = OrderedDict([("key1", "val1"), ("key2", "val2")])
result = parser.serialize(items)
# Verify round-trip: parse the serialized output
parsed = parser.parse(StringIO(result))
self.assertEqual(parsed, {"key1": "val1", "key2": "val2"})
def test_serialize_nested_section(self):
parser = configargparse.TomlConfigParser(["tool.section"])
try:
import toml
except ImportError:
self.skipTest("toml package not installed")
items = OrderedDict([("key1", "val1")])
result = parser.serialize(items)
parsed = parser.parse(StringIO(result))
self.assertEqual(parsed, {"key1": "val1"})
def test_serialize_no_sections(self):
parser = configargparse.TomlConfigParser([])
try:
import toml
except ImportError:
self.skipTest("toml package not installed")
items = OrderedDict([("key1", "val1")])
result = parser.serialize(items)
self.assertIn("key1", result)
def test_serialize_without_toml_package(self):
parser = configargparse.TomlConfigParser(["section"])
items = OrderedDict([("key1", "val1")])
# Mock tomllib import succeeding but toml import failing
import unittest.mock as mock
with mock.patch.dict(sys.modules, {"toml": None}):
with self.assertRaises(configargparse.ConfigFileParserMissingDependency):
parser.serialize(items)
class TestIniConfigParserSerialize(unittest.TestCase):
def test_serialize_basic(self):
parser = configargparse.IniConfigParser(["section"], False)
items = OrderedDict([("key1", "val1"), ("key2", "val2")])
result = parser.serialize(items)
# Verify round-trip
parsed = parser.parse(StringIO(result))
self.assertEqual(parsed, {"key1": "val1", "key2": "val2"})
def test_serialize_list_as_python_syntax(self):
parser = configargparse.IniConfigParser(["section"], False)
items = OrderedDict([("key1", ["a", "b", "c"])])
result = parser.serialize(items)
parsed = parser.parse(StringIO(result))
self.assertEqual(parsed, {"key1": ["a", "b", "c"]})
def test_serialize_list_multiline(self):
parser = configargparse.IniConfigParser(["section"], True)
items = OrderedDict([("key1", ["a", "b", "c"])])
result = parser.serialize(items)
# Should use multiline format
self.assertIn("\n", result.split("key1")[1])
def test_serialize_default_section(self):
parser = configargparse.IniConfigParser([], False)
items = OrderedDict([("key1", "val1")])
result = parser.serialize(items)
self.assertIn("key1", result)
def test_serialized_percent_values_read_back_unchanged(self):
for split_ml_text_to_list in (False, True):
parser = configargparse.IniConfigParser(["section"], split_ml_text_to_list)
for value in (
"%Y-%m-%d",
"50%",
"100%%",
"%(asctime)s %(message)s",
["50%", "%(x)s"],
):
with self.subTest(split=split_ml_text_to_list, value=value):
contents = parser.serialize({"key": value})
self.assertEqual(
parser.parse(StringIO(contents)),
OrderedDict([("key", value)]),
)
class TestCompositeConfigParser(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.TemporaryDirectory()
self.old_cwd = os.getcwd()
os.chdir(self.tmpdir.name)
self.parser = configargparse.ArgParser(
description="test",
default_config_files=["config.yaml", "config.toml", "config.ini"],
config_file_parser_class=configargparse.CompositeConfigParser(
[
configargparse.TomlConfigParser(["section"]),
configargparse.YAMLConfigFileParser,
configargparse.IniConfigParser(["section"], False),
]
),
)
self.parser.add_argument("--config", is_config_file=True)
self.parser.add_argument("--key1", type=str)
self.parser.add_argument("--key2", type=str)
def tearDown(self):
os.chdir(self.old_cwd)
self.tmpdir.cleanup()
def write_yaml_file(self, content="[section]\nkey1: yaml1\nkey2: yaml2"):
with open("config.yaml", "w") as f:
f.write(content)
def write_ini_file(
self, content="[section]\nkey1=ini1\nkey2=ini2\n; this is an ini comment"
):
with open("config.ini", "w") as f:
f.write(content)
def write_toml_file(
self,
content="[section]\nkey1 = 'toml1'\nkey2 = 'toml2'\nspecial.key = { a = 1 }\n# this is a toml comment",
):
with open("config.toml", "w") as f:
f.write(content)
def write_toml_file_extra(self):
self.write_toml_file()
with open("config.toml", "a") as f:
f.write("\nkey3 = 'toml3'\nkey4 = 'toml4'")
def test_plain(self):
self.assertEqual(
vars(self.parser.parse_args([])),
{"config": None, "key1": None, "key2": None},
)
@unittest.expectedFailure # unknown fields should be ignored
def test_with_all_configs(self):
self.write_yaml_file()
self.write_ini_file()
self.write_toml_file()
self.assertEqual(
vars(self.parser.parse_args([])),
{"config": None, "key1": "ini1", "key2": "ini2"},
)
@unittest.expectedFailure # unknown fields should be ignored
def test_with_all_configs_override(self):
self.write_yaml_file()
self.write_ini_file()
self.write_toml_file()
self.assertEqual(
vars(self.parser.parse_args(["--key1", "val1"])),
{"config": None, "key1": "val1", "key2": "ini2"},
)
def test_missing_primary_config(self):
self.write_yaml_file()
self.assertEqual(
vars(self.parser.parse_args([])),
{"config": None, "key1": "yaml1", "key2": "yaml2"},
)
@unittest.expectedFailure # unknown fields should be ignored
def test_toml(self):
self.write_yaml_file()
self.write_toml_file()
self.assertEqual(
vars(self.parser.parse_args([])),
{"config": None, "key1": "toml1", "key2": "toml2"},
)
@unittest.expectedFailure # unknown fields should be ignored
def test_override_primary_config(self):
self.write_yaml_file()
self.write_ini_file()
self.write_toml_file()
self.assertEqual(
vars(self.parser.parse_args(["--config", "config.yaml"])),
{"config": "config.yaml", "key1": "yaml1", "key2": "yaml2"},
)
def test_toml_extra(self):
self.write_yaml_file()
self.write_ini_file()
self.write_toml_file_extra()
with self.assertRaises(SystemExit):
self.parser.parse_args([])
def test_composite_warns_if_missing_dependency(self):
self.write_yaml_file()
self.write_ini_file()
with mock.patch.dict(sys.modules, {"toml": None, "tomllib": None}):
with self.assertWarnsRegex(UserWarning, "TomlConfigParser"):
ns = self.parser.parse_args([])
# the parser that could not run is reported, but the chain still works
self.assertEqual(ns.key1, "ini1")
def test_composite_warns_if_wrong_order(self):
with self.assertWarns(SyntaxWarning):
composite = configargparse.CompositeConfigParser(
[
configargparse.IniConfigParser(["section"], False),
configargparse.TomlConfigParser(["section"]),
]
)()
def test_composite_serialize_delegates_to_first_parser(self):
composite = configargparse.CompositeConfigParser(
[
configargparse.IniConfigParser(["section"], False),
configargparse.DefaultConfigFileParser,
]
)()
items = OrderedDict([("key1", "val1"), ("key2", "val2")])
result = composite.serialize(items)
# Should use INI format (first parser)
self.assertIn("[section]", result)
self.assertIn("key1 = val1", result)
def test_composite_serialize_empty_parsers(self):
composite = configargparse.CompositeConfigParser([])()
with self.assertRaises(configargparse.ConfigFileParserException):
composite.serialize(OrderedDict())
class TestCallableDefaultConfigFiles(TestCase):
def testCallableReturningStringIO(self):
def loader():
return StringIO("genome=hg19\n")
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
ns = self.parse("")
self.assertEqual(ns.genome, "hg19")
def testCallableReturningNoneRaises(self):
def empty_loader():
return None
self.initParser(default_config_files=[empty_loader])
self.add_arg("--genome")
with self.assertRaisesRegex(TypeError, r"empty_loader.*returned None"):
self.parse("")
def testCallableRaisingIsWrapped(self):
def boom_loader():
raise RuntimeError("boom")
self.initParser(default_config_files=[boom_loader])
self.add_arg("--genome")
with self.assertRaises(configargparse.ConfigFileParserException) as ctx:
self.parse("")
self.assertIn("boom_loader", str(ctx.exception))
self.assertIn("boom", str(ctx.exception))
self.assertIsInstance(ctx.exception.__cause__, RuntimeError)
self.assertEqual(str(ctx.exception.__cause__), "boom")
def testCallableRaisingMultiArgException(self):
# Wrapping must not depend on the original exception class accepting a
# single string arg. CalledProcessError requires (returncode, cmd) and
# would have crashed type(e)(...) before this fix.
import subprocess
def boom_loader():
raise subprocess.CalledProcessError(1, ["cmd"])
self.initParser(default_config_files=[boom_loader])
self.add_arg("--genome")
with self.assertRaises(configargparse.ConfigFileParserException) as ctx:
self.parse("")
self.assertIn("boom_loader", str(ctx.exception))
self.assertIsInstance(ctx.exception.__cause__, subprocess.CalledProcessError)
def testCallableStreamNameAssignmentFailsRaises(self):
closed = []
class NoNameStream:
__slots__ = ("_closed",)
def __init__(self_inner):
self_inner._closed = False
def read(self_inner):
return ""
def __iter__(self_inner):
return iter([])
def close(self_inner):
self_inner._closed = True
closed.append(self_inner)
# name lives in NoNameStream's __slots__-less namespace, so any attempt
# to assign `stream.name = ...` raises AttributeError.
def slot_loader():
return NoNameStream()
self.initParser(default_config_files=[slot_loader])
self.add_arg("--genome")
with self.assertRaises(configargparse.ConfigFileParserException) as ctx:
self.parse("")
self.assertIn("slot_loader", str(ctx.exception))
self.assertIn(".name attribute could not be set", str(ctx.exception))
self.assertIsInstance(ctx.exception.__cause__, AttributeError)
# The returned stream must still be closed by the parser even though
# the .name assignment failed.
self.assertEqual(len(closed), 1)
self.assertTrue(closed[0]._closed)
def testCallableInvokedEachParse(self):
calls = {"count": 0}
def loader():
calls["count"] += 1
return StringIO("genome=hg19\n")
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
self.parse("")
self.parse("")
self.parse("")
self.assertEqual(calls["count"], 3)
def testCallableStreamIsClosed(self):
class TrackingStringIO(StringIO):
instances = []
def __init__(self_inner, *a, **kw):
super().__init__(*a, **kw)
self_inner.was_closed = False
TrackingStringIO.instances.append(self_inner)
def close(self_inner):
self_inner.was_closed = True
super().close()
def loader():
return TrackingStringIO("genome=hg19\n")
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
self.parse("")
self.assertEqual(len(TrackingStringIO.instances), 1)
self.assertTrue(TrackingStringIO.instances[0].was_closed)
def testMixedStringsAndCallables(self):
temp_cfg = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".ini")
temp_cfg.write("genome=from_file\n")
temp_cfg.flush()
temp_cfg.close()
def loader():
return StringIO("genome=from_callable\n")
# Later entries override earlier ones, so the callable wins.
self.initParser(default_config_files=[temp_cfg.name, loader])
self.add_arg("--genome")
ns = self.parse("")
self.assertEqual(ns.genome, "from_callable")
# Reverse order: the file should win.
self.initParser(default_config_files=[loader, temp_cfg.name])
self.add_arg("--genome")
ns = self.parse("")
self.assertEqual(ns.genome, "from_file")
os.unlink(temp_cfg.name)
def testCallableWithRealFile(self):
temp_cfg = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".ini")
temp_cfg.write("genome=hg19\n")
temp_cfg.flush()
temp_cfg.close()
opened = []
def loader():
f = open(temp_cfg.name)
opened.append(f)
return f
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
ns = self.parse("")
self.assertEqual(ns.genome, "hg19")
self.assertEqual(len(opened), 1)
self.assertTrue(opened[0].closed)
os.unlink(temp_cfg.name)
def testInvalidEntryType(self):
with self.assertRaisesRegex(TypeError, r"default_config_files\[0\]"):
configargparse.ArgParser(default_config_files=[123])
with self.assertRaisesRegex(TypeError, r"default_config_files\[1\]"):
configargparse.ArgParser(default_config_files=["ok.ini", 42])
def testFormatHelpRendersCallableName(self):
def my_loader():
return StringIO("")
self.initParser(default_config_files=[my_loader])
self.add_arg("--genome")
help_text = self.format_help()
self.assertIn("my_loader", help_text)
self.assertNotIn(""; without disambiguation
# by index they'd merge into one source key in format_values output.
l1 = lambda: StringIO("genome=hg19\n")
l2 = lambda: StringIO("vcf=foo.vcf\n")
self.initParser(default_config_files=[l1, l2])
self.add_arg("--genome")
self.add_arg("--vcf")
self.parse("")
sources = self.parser.get_source_to_settings_dict()
config_file_sources = [
k for k in sources if k.startswith(configargparse._CONFIG_FILE_SOURCE_KEY)
]
self.assertEqual(len(config_file_sources), 2)
# format_values should not crash either
self.parser.format_values()
def testEarlierStreamsClosedWhenLaterEntryFails(self):
opened = []
class TrackingStringIO(StringIO):
def __init__(self_inner, *a, **kw):
super().__init__(*a, **kw)
self_inner.was_closed = False
opened.append(self_inner)
def close(self_inner):
self_inner.was_closed = True
super().close()
def good_loader():
return TrackingStringIO("genome=hg19\n")
def bad_loader():
raise RuntimeError("nope")
self.initParser(default_config_files=[good_loader, bad_loader])
self.add_arg("--genome")
with self.assertRaises(configargparse.ConfigFileParserException):
self.parse("")
self.assertEqual(len(opened), 1)
self.assertTrue(opened[0].was_closed)
def testEarlierStreamsClosedWhenParserRaisesUnexpectedException(self):
# X5: a custom parser raising a non-ConfigFileParserException must not
# leak streams that were opened but not yet processed.
class BadParser(configargparse.ConfigFileParser):
def get_syntax_description(self):
return ""
def parse(self_inner, stream):
raise ValueError("parser bug")
def serialize(self_inner, items):
return ""
opened = []
class TrackingStringIO(StringIO):
def __init__(self_inner, *a, **kw):
super().__init__(*a, **kw)
self_inner.was_closed = False
opened.append(self_inner)
def close(self_inner):
self_inner.was_closed = True
super().close()
def loader_a():
return TrackingStringIO("genome=hg19\n")
def loader_b():
return TrackingStringIO("genome=hg20\n")
self.initParser(
default_config_files=[loader_a, loader_b],
config_file_parser_class=BadParser,
)
self.add_arg("--genome")
with self.assertRaises(ValueError):
self.parse("")
self.assertEqual(len(opened), 2)
self.assertTrue(all(s.was_closed for s in opened))
def testFormatValuesHandlesPipeInCallableName(self):
def loader():
s = StringIO("genome=hg19\n")
s.name = "weird|name|with|pipes"
return s
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
self.parse("")
# Must not raise on pipe characters in the source name.
output = self.parser.format_values()
self.assertIn("weird|name|with|pipes", output)
def testPathLikeAndCallableEntryTreatedAsPath(self):
# An object that is both os.PathLike and callable should be treated as
# a path; the callable branch must not be taken first.
temp_cfg = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".ini")
temp_cfg.write("genome=hg19\n")
temp_cfg.flush()
temp_cfg.close()
class CallablePath:
def __init__(self_inner, p):
self_inner._p = p
def __fspath__(self_inner):
return self_inner._p
def __call__(self_inner):
# Must NOT be called; if we end up here the dispatch is wrong
# and the test should fail loudly.
raise AssertionError(
"callable branch taken for a PathLike+callable entry"
)
self.initParser(default_config_files=[CallablePath(temp_cfg.name)])
self.add_arg("--genome")
ns = self.parse("")
self.assertEqual(ns.genome, "hg19")
os.unlink(temp_cfg.name)
def testDefaultStreamsClosedWhenUserConfigPhaseRaises(self):
# X3: when an is_config_file_arg's type= callback raises during the
# inner argparse phase of _open_config_files, the default config
# streams already opened earlier must be closed.
opened = []
class TrackingStringIO(StringIO):
def __init__(self_inner, *a, **kw):
super().__init__(*a, **kw)
self_inner.was_closed = False
opened.append(self_inner)
def close(self_inner):
self_inner.was_closed = True
super().close()
def loader():
return TrackingStringIO("genome=hg19\n")
def bad_type(value):
raise RuntimeError("type exploded")
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
self.add_arg("--config", is_config_file_arg=True, type=bad_type)
with self.assertRaises(RuntimeError):
self.parse(["--config", "anything"])
self.assertEqual(len(opened), 1)
self.assertTrue(opened[0].was_closed)
def testTwoCallableStreamsWithSameNameDoNotCollide(self):
# X1: even if two callables both return streams whose .name attribute
# is set to the same string, they must remain distinct sources.
def loader_a():
s = StringIO("genome=hg19\n")
s.name = "shared"
return s
def loader_b():
s = StringIO("vcf=foo.vcf\n")
s.name = "shared"
return s
self.initParser(default_config_files=[loader_a, loader_b])
self.add_arg("--genome")
self.add_arg("--vcf")
self.parse("")
sources = self.parser.get_source_to_settings_dict()
config_file_sources = [
k for k in sources if k.startswith(configargparse._CONFIG_FILE_SOURCE_KEY)
]
self.assertEqual(len(config_file_sources), 2)
def testCallableStreamNameMatchingGeneratedFormatDoesNotCollide(self):
# X4: a callable whose returned stream's .name happens to match the
# library's generated "[]" pattern must not collide
# with another callable that would otherwise generate the same name.
def loader_with_clashing_name():
s = StringIO("genome=hg19\n")
s.name = "loader[1]" # matches what the lib would generate
return s
def loader(): # __name__ == "loader"; at index 1
return StringIO("vcf=foo.vcf\n")
self.initParser(default_config_files=[loader_with_clashing_name, loader])
self.add_arg("--genome")
self.add_arg("--vcf")
self.parse("")
sources = self.parser.get_source_to_settings_dict()
config_file_sources = [
k for k in sources if k.startswith(configargparse._CONFIG_FILE_SOURCE_KEY)
]
self.assertEqual(len(config_file_sources), 2)
def testStreamClosedExactlyOnceOnSuccess(self):
# X2: on a successful parse, each stream's close() must be called
# exactly once (the previous design called it twice — once in the
# per-stream finally and once in the outer cleanup finally).
close_calls = []
class CountingStringIO(StringIO):
def close(self_inner):
close_calls.append(self_inner)
super().close()
def loader():
return CountingStringIO("genome=hg19\n")
self.initParser(default_config_files=[loader])
self.add_arg("--genome")
self.parse("")
self.assertEqual(len(close_calls), 1)
def testFormatHelpShowsPathForPathLikeAndCallable(self):
# X3: an entry that's both PathLike and callable is treated as a path
# at runtime; format_help must label it the same way (not as
# ).
class CallablePath:
def __init__(self_inner, p):
self_inner._p = p
def __fspath__(self_inner):
return self_inner._p
def __call__(self_inner):
raise AssertionError("should not be called")
self.initParser(default_config_files=[CallablePath("/tmp/example.ini")])
self.add_arg("--genome")
help_text = self.format_help()
self.assertIn("/tmp/example.ini", help_text)
self.assertNotIn("", help_text)
def testFormatHelpHandlesBytesReturningPathLike(self):
# PEP 519 allows __fspath__() to return bytes. format_help must not
# crash when joining bytes path entries with str strings.
class BytesPath:
def __fspath__(self_inner):
return b"/tmp/bytes-example.ini"
self.initParser(default_config_files=[BytesPath()])
self.add_arg("--genome")
# Just must not raise; the path gets rendered (subject to textwrap,
# so we check only for stable substrings).
help_text = self.format_help()
# textwrap may insert a newline mid-path, so check fragments only
self.assertIn("/tmp/bytes", help_text.replace("\n", ""))
self.assertIn("example.ini", help_text)
def testFormatHelpHandlesMalformedPathLike(self):
# A PathLike whose __fspath__ returns something other than str/bytes
# would cause os.fspath() to raise TypeError. format_help must not
# crash on invalid input — fall back to repr().
class BrokenPath:
def __fspath__(self_inner):
return None
self.initParser(default_config_files=[BrokenPath()])
self.add_arg("--genome")
# Must not raise. Output should at least not contain a Python
# traceback marker; we just confirm it produces some text.
help_text = self.format_help()
self.assertIsInstance(help_text, str)
self.assertGreater(len(help_text), 0)
class TestStoreFalseConfigOutput(unittest.TestCase):
def make_parser(self, default=True):
parser = configargparse.ArgumentParser()
parser.add_argument(
"-n",
"--no-feature",
"--disable-feature",
action="store_false",
dest="feature",
default=default,
env_var="CONFIGARGPARSE_TEST_NO_FEATURE",
)
parser.add_argument("--label", env_var="CONFIGARGPARSE_TEST_LABEL")
return parser
def assert_round_trip(self, parser, namespace, reader):
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "settings.conf")
with captured_output():
parser.write_config_file(namespace, [path])
with open(path) as config_file:
contents = config_file.read()
restored = reader.parse_args([], config_file_contents=contents, env_vars={})
self.assertEqual(vars(restored), vars(namespace))
# assertEqual alone would accept 0 coming back as False
for name, value in vars(namespace).items():
self.assertIs(type(getattr(restored, name)), type(value), name)
return contents
def test_store_false_command_line_round_trip(self):
for default in (True, False):
for option in ("-n", "--no-feature", "--disable-feature"):
with self.subTest(default=default, option=option):
parser = self.make_parser(default)
namespace = parser.parse_args([option], env_vars={})
self.assertFalse(namespace.feature)
self.assert_round_trip(parser, namespace, self.make_parser(default))
def test_store_false_environment_round_trip(self):
for default in (True, False):
for value in ("true", "false"):
with self.subTest(default=default, value=value):
parser = self.make_parser(default)
with mock.patch.dict(
os.environ,
{
"CONFIGARGPARSE_TEST_NO_FEATURE": value,
"CONFIGARGPARSE_TEST_LABEL": "example",
},
):
namespace = parser.parse_args([])
self.assertEqual(namespace.feature, default and value == "false")
self.assertEqual(namespace.label, "example")
self.assert_round_trip(parser, namespace, self.make_parser(default))
def test_store_false_config_round_trip(self):
for default in (True, False):
for value in ("true", "false"):
with self.subTest(default=default, value=value):
parser = self.make_parser(default)
namespace = parser.parse_args(
[], config_file_contents="no-feature = " + value, env_vars={}
)
self.assert_round_trip(parser, namespace, self.make_parser(default))
def test_non_boolean_store_false_default_round_trip(self):
# 1 and "yes" are truthy, so writing them as-is would invoke the flag
for default in (0, 1, "yes"):
with self.subTest(default=default):
parser = self.make_parser(default)
namespace = parser.parse_args(
[],
env_vars={
"CONFIGARGPARSE_TEST_NO_FEATURE": "false",
"CONFIGARGPARSE_TEST_LABEL": "example",
},
)
self.assertIs(namespace.feature, default)
self.assert_round_trip(parser, namespace, self.make_parser(default))
def test_store_false_defaults_are_not_added(self):
for default in (True, False):
with self.subTest(default=default):
parser = self.make_parser(default)
namespace = parser.parse_args([], env_vars={})
contents = self.assert_round_trip(
parser, namespace, self.make_parser(default)
)
self.assertEqual(contents, "")
def test_other_boolean_actions_round_trip(self):
actions = [("store_true", False, ["--feature"])]
if hasattr(argparse, "BooleanOptionalAction"):
actions += [
(argparse.BooleanOptionalAction, True, ["--no-feature"]),
(argparse.BooleanOptionalAction, False, ["--feature"]),
]
for action, default, args in actions:
with self.subTest(action=action, default=default):
parser = configargparse.ArgumentParser()
parser.add_argument("--feature", action=action, default=default)
namespace = parser.parse_args(args, env_vars={})
reader = configargparse.ArgumentParser()
reader.add_argument("--feature", action=action, default=default)
self.assert_round_trip(parser, namespace, reader)
def test_store_const_round_trip(self):
def make_parser():
parser = configargparse.ArgumentParser()
parser.add_argument(
"--fast",
action="store_const",
const="fast",
dest="mode",
default="slow",
env_var="CONFIGARGPARSE_TEST_FAST",
)
parser.add_argument("--label", env_var="CONFIGARGPARSE_TEST_LABEL")
return parser
cases = [
(["--fast"], {}, "fast", "fast = true\n"),
(
[],
{"CONFIGARGPARSE_TEST_FAST": "true", "CONFIGARGPARSE_TEST_LABEL": "x"},
"fast",
"fast = true\nlabel = x\n",
),
(
[],
{"CONFIGARGPARSE_TEST_FAST": "false", "CONFIGARGPARSE_TEST_LABEL": "x"},
"slow",
"fast = false\nlabel = x\n",
),
]
for args, env_vars, expected_mode, expected_contents in cases:
with self.subTest(args=args, env_vars=env_vars):
parser = make_parser()
namespace = parser.parse_args(args, env_vars=env_vars)
self.assertEqual(namespace.mode, expected_mode)
contents = self.assert_round_trip(parser, namespace, make_parser())
self.assertEqual(contents, expected_contents)
class TestConfigparserDefaultSection(TestCase):
def test_default_only_values(self):
parser = configargparse.ConfigparserConfigFileParser()
contents = (
"[DEFAULT]\nName = alice\nlabel = %(name)s\nempty =\n"
"items = ['a', 'b']\nmessage = first\n second\n"
)
self.assertEqual(
parser.parse(StringIO(contents)),
OrderedDict(
[
("name", "alice"),
("label", "alice"),
("empty", ""),
("items", ["a", "b"]),
("message", "first second"),
]
),
)
def test_saved_config_round_trip(self):
parser = self.initParser(
config_file_parser_class=configargparse.ConfigparserConfigFileParser
)
parser.add_argument("--name")
parser.add_argument("--count", type=int)
parser.add_argument("--matrix", nargs="+", type=json.loads)
expected = parser.parse_args(
["--name", "alice", "--count", "3", "--matrix", "[1, 2]", "[3, 4]"]
)
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "saved.ini")
parser.write_config_file(expected, [path])
with open(path) as stream:
contents = stream.read()
actual = parser.parse_args([], config_file_contents=contents)
self.assertEqual(actual, expected)
def test_blank_line_in_value_does_not_start_a_new_key(self):
# how an earlier version of serialize() wrote a value with a blank line
contents = "[DEFAULT]\nnotes = line1\n\t\n\tupload-url = https://x\n"
self.assertEqual(
configargparse.ConfigparserConfigFileParser().parse(StringIO(contents)),
OrderedDict([("notes", "line1 upload-url = https://x")]),
)
def test_named_sections_keep_default_overrides(self):
parser = configargparse.ConfigparserConfigFileParser()
contents = (
"[DEFAULT]\nname = default\nshared = value\n"
"[first]\nname = alice\n[first_extra]\nname = bob\n"
)
self.assertEqual(
parser.parse(StringIO(contents)),
OrderedDict([("name", "bob"), ("shared", "value")]),
)
def test_serialized_values_read_back_unchanged(self):
parser = configargparse.ConfigparserConfigFileParser()
for value, expected in (
("file[0-9].txt", "file[0-9].txt"),
("[value6.1, value6.2]", "[value6.1, value6.2]"),
(["a", "50%"], ["a", "50%"]),
("50%", "50%"),
("100%%", "100%%"),
("%(asctime)s %(message)s", "%(asctime)s %(message)s"),
("a;b", "a;b"),
("#ff0000", "#ff0000"),
(";", ";"),
# in a list or a quoted string, "#" and ";" are written as escapes
(["issue #12", "b ; c"], ["issue #12", "b ; c"]),
("Results [v2] ; final", "Results [v2] ; final"),
([pathlib.Path("a.txt"), float("inf")], ["a.txt", "inf"]),
([["a", 1, pathlib.Path("b.txt")], ["c"]], [["a", 1, "b.txt"], ["c"]]),
# a tuple reads back as the string the option's type was given
((224, 224), "(224, 224)"),
([(1, 2), (3, 4)], [(1, 2), (3, 4)]),
("line1\nline2", "line1 line2"),
# a blank line or a lone \r must not start a new key
("x\n\nother = injected", "x other = injected"),
("x\rother = injected", "x other = injected"),
):
with self.subTest(value=value), warnings.catch_warnings():
# a value that reads back unchanged must not be warned about
warnings.simplefilter("error")
# newline=None reads a lone \r as a line break, the way open()
# does when parse_args reads a config file
stream = StringIO(parser.serialize({"key": value}), newline=None)
self.assertEqual(parser.parse(stream), OrderedDict([("key", expected)]))
def test_serialize_warns_about_values_read_back_cut_short(self):
parser = configargparse.ConfigparserConfigFileParser()
for value in ("run #1", "a ; b", "a\t#b"):
with self.subTest(value=value):
with self.assertWarnsRegex(
UserWarning, "value of key .*cut short"
) as caught:
contents = parser.serialize({"key": value})
self.assertIn("\nkey=", contents)
# the value may be a secret, so the warning must not show it
self.assertNotIn(str(value), str(caught.warning))
def test_bad_interpolation_raises_config_file_parser_exception(self):
parser = configargparse.ConfigparserConfigFileParser()
for contents, problem in (
("[DEFAULT]\npct = 50%secret\n", "isn't '%%'.*Write %%"),
("[section]\npct = 50%secret\n", "isn't '%%'.*Write %%"),
(
"[section]\nlabel = %(missing)ssecret\n",
"isn't in the same section or in \\[DEFAULT\\].*Write %%",
),
(
"[DEFAULT]\npath = /base\n[job]\npath = %(path)ssecret\n",
"refer back to it",
),
):
with self.subTest(contents=contents):
with self.assertRaisesRegex(
configargparse.ConfigFileParserException,
"Couldn't parse config file value for (pct|label|path): .*"
+ problem,
) as caught:
parser.parse(StringIO(contents))
# the value may be a secret, so neither the message nor a
# traceback (which would show a chained exception) may show it
exception = caught.exception
self.assertNotIn(
"secret",
"".join(
traceback.format_exception(
type(exception), exception, exception.__traceback__
)
),
)
class TestFalseFlagPrecedence(unittest.TestCase):
false_values = ("false", "no", "off", "0", "FALSE")
actions = (("store_true", False), ("store_false", True))
def test_environment_overrides_config(self):
for action_name, expected in self.actions:
for value in self.false_values:
for config_key in ("feature", "alias"):
with self.subTest(action=action_name, value=value, key=config_key):
parser = configargparse.ArgumentParser()
action = parser.add_argument(
"--feature",
"--alias",
action=action_name,
env_var="FEATURE",
)
result = parser.parse_args(
[],
env_vars={"FEATURE": value},
config_file_contents=config_key + "=true",
)
self.assertIs(result.feature, expected)
self.assertEqual(
parser.get_source_to_settings_dict(),
{"environment_variables": {"FEATURE": (action, value)}},
)
self.assertIn("Environment Variables:", parser.format_values())
self.assertIn(value, parser.format_values())
self.assertNotIn("Config File", parser.format_values())
def test_later_config_overrides_earlier_config(self):
with tempfile.TemporaryDirectory() as directory:
lower = pathlib.Path(directory) / "default.ini"
higher = pathlib.Path(directory) / "user.ini"
lower.write_text("feature=true\n")
for action_name, expected in self.actions:
for value in self.false_values:
with self.subTest(action=action_name, value=value):
higher.write_text("alias=" + value + "\n")
parser = configargparse.ArgumentParser(
default_config_files=[lower, higher]
)
action = parser.add_argument(
"--feature", "--alias", action=action_name
)
self.assertIs(
parser.parse_args([], env_vars={}).feature, expected
)
self.assertEqual(
parser.get_source_to_settings_dict(),
{"config_file|" + str(higher): {"alias": (action, value)}},
)
self.assertNotIn(str(lower), parser.format_values())
def test_command_line_overrides_false_environment_and_config(self):
for action_name, expected in self.actions:
for value in self.false_values:
for option in ("-f", "--feature", "--alias"):
with self.subTest(action=action_name, value=value, option=option):
parser = configargparse.ArgumentParser()
parser.add_argument(
"-f",
"--feature",
"--alias",
action=action_name,
env_var="FEATURE",
)
result = parser.parse_args(
[option],
env_vars={"FEATURE": value},
config_file_contents="feature=false",
)
self.assertIs(result.feature, not expected)
self.assertEqual(
parser.get_source_to_settings_dict(),
{"command_line": {"": (None, [option])}},
)
def test_false_does_not_replace_custom_default(self):
for action_name, _ in self.actions:
with self.subTest(action=action_name):
parser = configargparse.ArgumentParser()
parser.add_argument(
"--feature", action=action_name, default="unset", env_var="FEATURE"
)
result = parser.parse_args(
[],
env_vars={"FEATURE": "false"},
config_file_contents="feature=true",
)
self.assertEqual(result.feature, "unset")
def test_false_does_not_select_mutually_exclusive_member(self):
parser = configargparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--feature", action="store_true", env_var="FEATURE")
group.add_argument("--other", action="store_true")
result = parser.parse_args(
[],
env_vars={"FEATURE": "false"},
config_file_contents="feature=true\nother=true",
)
self.assertFalse(result.feature)
self.assertTrue(result.other)
# Two active members within a single source must still conflict.
with self.assertRaises(SystemExit), captured_output():
parser.parse_args(
[], env_vars={}, config_file_contents="feature=true\nother=true"
)
# A false value alone must not satisfy a required group.
with self.assertRaises(SystemExit), captured_output():
parser.parse_args([], env_vars={"FEATURE": "false"})
def test_shared_environment_variable_overrides_both_actions(self):
parser = configargparse.ArgumentParser()
parser.add_argument("--first", action="store_true", env_var="FEATURE")
parser.add_argument("--second", action="store_true", env_var="FEATURE")
result = parser.parse_args(
[],
env_vars={"FEATURE": "false"},
config_file_contents="first=true\nsecond=true",
)
self.assertFalse(result.first)
self.assertFalse(result.second)
def test_flag_actions_reset_between_parses(self):
parser = configargparse.ArgumentParser()
parser.add_argument("--feature", action="store_true", env_var="FEATURE")
self.assertFalse(
parser.parse_args(
[], env_vars={"FEATURE": "false"}, config_file_contents="feature=true"
).feature
)
self.assertTrue(
parser.parse_args(
[], env_vars={}, config_file_contents="feature=true"
).feature
)
def test_empty_environment_value_still_falls_back_to_config(self):
parser = configargparse.ArgumentParser()
parser.add_argument("--items", nargs="+", env_var="ITEMS")
result = parser.parse_args(
[], env_vars={"ITEMS": ""}, config_file_contents="items=[one,two]"
)
self.assertEqual(result.items, ["one", "two"])
self.assertNotIn("environment_variables", parser.get_source_to_settings_dict())
def test_empty_list_does_not_override_lower_priority_list(self):
# only flags are tracked, so an empty list still falls back to lower
# priority sources, as it did before false flags were tracked
parser = configargparse.ArgumentParser()
parser.add_argument("--item", action="append", env_var="ITEM")
result = parser.parse_args(
[], env_vars={"ITEM": "[]"}, config_file_contents="item = [a]"
)
self.assertEqual(result.item, ["a"])
with tempfile.TemporaryDirectory() as directory:
lower = pathlib.Path(directory) / "default.ini"
higher = pathlib.Path(directory) / "user.ini"
lower.write_text("item = [a]\n")
higher.write_text("item = []\n")
parser = configargparse.ArgumentParser(default_config_files=[lower, higher])
parser.add_argument("--item", action="append")
self.assertEqual(parser.parse_args([], env_vars={}).item, ["a"])
def test_zero_count_overrides_lower_priority_count(self):
# a count arg is a flag too, and "0" is one of its false values
parser = configargparse.ArgumentParser()
parser.add_argument("-v", "--verbose", action="count", env_var="VERBOSE")
result = parser.parse_args(
[], env_vars={"VERBOSE": "0"}, config_file_contents="verbose = 3"
)
self.assertIsNone(result.verbose)
################################################################################
# since configargparse should work as a drop-in replacement for argparse
# in all situations, run argparse unittests on configargparse by modifying
# their source code to use configargparse.ArgumentParser
try:
import test.test_argparse
# Sig = test.test_argparse.Sig
# NS = test.test_argparse.NS
except ImportError:
logging.error(
"\n\n"
"============================\n"
"ERROR: Many tests couldn't be run because 'import test.test_argparse' "
"failed. Try building/installing python from source rather than through"
" a package manager.\n"
"============================\n"
)
else:
test_argparse_source_file = inspect.getsourcefile(test.test_argparse)
test_argparse_source_code = inspect.getsource(test.test_argparse)
configargparse_dir = os.path.dirname(
os.path.abspath(configargparse.__file__)
).replace("\\", "/")
test_argparse_source_code = (
test_argparse_source_code.replace(
"argparse.ArgumentParser", "configargparse.ArgumentParser"
)
.replace("TestHelpFormattingMetaclass", "_TestHelpFormattingMetaclass")
.replace("test_main", "_test_main")
.replace(
"import argparse\n parser = configargparse.ArgumentParser()",
"import sys; "
f"sys.path.insert(0, {configargparse_dir!r}); "
"import configargparse\n parser = configargparse.ArgumentParser()",
)
.replace(
"self.assertEqual(cm.filename, __file__)",
"self.assertEqual(cm.filename, test_argparse_source_file)",
)
)
# pytest tries to collect tests from TestHelpFormattingMetaclass, and
# test_main, and raises a warning when it finds it's not a test class
# nor test function. Renaming TestHelpFormattingMetaclass and test_main
# prevents pytest from trying.
# Python 3.14+ TestProgName runs its source in an isolated (-I) subprocess,
# which ignores PYTHONPATH and the working directory, so the script puts
# the directory of the configargparse under test on sys.path itself (with
# forward slashes so Windows backslashes aren't read as string escapes),
# on the same line as the import to keep line numbers unchanged.
# Several 3.14+ tests also check that a warning's filename is the test
# file, so the exec'd code is compiled under the upstream test file's path
# (which also gives tracebacks the right file and line numbers) and
# compared against that path.
# run or debug a subset of the argparse tests
# test_argparse_source_code = test_argparse_source_code.replace(
# "(TestCase)", "").replace(
# "(ParserTestCase)", "").replace(
# "(HelpTestCase)", "").replace(
# ", TestCase", "").replace(
# ", ParserTestCase", "")
# test_argparse_source_code = test_argparse_source_code.replace(
# "class TestMessageContentError", "class TestMessageContentError(TestCase)")
exec(compile(test_argparse_source_code, test_argparse_source_file, "exec"))
# print argparse unittest source code
def print_source_code(source_code, line_numbers, context_lines=10):
for n in line_numbers:
logging.debug("##### Code around line %s #####" % n)
lines_to_print = set(range(n - context_lines, n + context_lines))
for n2, line in enumerate(source_code.split("\n"), 1):
if n2 in lines_to_print:
logging.debug("%s %5d: %s" % ("**" if n2 == n else " ", n2, line))
# print_source_code(test_argparse_source_code, [4540, 4565])
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1793144646.931062
configargparse-1.9.0/tests/test_end_of_options.py 0000644 0001751 0001751 00000012506 15270233507 021751 0 ustar 00runner runner import contextlib
import io
import unittest
import configargparse
class TestEndOfOptions(unittest.TestCase):
def test_positional_option_names_do_not_override_other_sources(self):
for source in ("environment", "config"):
for prefix in ("-", "+"):
long_option = prefix * 2 + "level"
short_option = prefix + "l"
for positionals in (
[long_option],
[long_option + "=positional"],
[short_option],
[short_option + "=positional"],
["--", long_option],
):
with self.subTest(
source=source, prefix=prefix, positionals=positionals
):
parser = configargparse.ArgumentParser(prefix_chars=prefix)
parser.add_argument(
short_option, long_option, env_var="LEVEL", required=True
)
parser.add_argument("files", nargs="+")
kwargs = (
{"env_vars": {"LEVEL": "info"}}
if source == "environment"
else {
"config_file_contents": "level = info",
"env_vars": {},
}
)
result = parser.parse_args(["--"] + positionals, **kwargs)
self.assertEqual(result.level, "info")
self.assertEqual(result.files, positionals)
# A real option before the marker still takes precedence.
result = parser.parse_args(
[long_option, "debug", "--"] + positionals, **kwargs
)
self.assertEqual(result.level, "debug")
self.assertEqual(result.files, positionals)
def test_positional_group_member_does_not_override_other_sources(self):
for source in ("environment", "config"):
with self.subTest(source=source):
parser = configargparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--json", action="store_true", env_var="JSON")
group.add_argument("--text", action="store_true")
parser.add_argument("files", nargs="+")
kwargs = (
{"env_vars": {"JSON": "true"}}
if source == "environment"
else {"config_file_contents": "json = true", "env_vars": {}}
)
result = parser.parse_args(["--", "--text"], **kwargs)
self.assertTrue(result.json)
self.assertFalse(result.text)
self.assertEqual(result.files, ["--text"])
def test_positional_option_name_does_not_hide_unknown_config_key(self):
parser = configargparse.ArgumentParser()
parser.add_argument("files", nargs="+")
result, unknown = parser.parse_known_args(
["--", "--extra"], config_file_contents="extra = config", env_vars={}
)
self.assertEqual(result.files, ["--extra"])
self.assertEqual(unknown, ["--extra=config"])
def test_positional_option_name_does_not_change_default_source(self):
parser = configargparse.ArgumentParser()
parser.add_argument("--level", default="warning")
parser.add_argument("files", nargs="+")
result = parser.parse_args(["--", "--level"], env_vars={})
self.assertEqual(result.level, "warning")
self.assertEqual(result.files, ["--level"])
settings = parser.get_source_to_settings_dict()
self.assertEqual(settings["defaults"]["--level"][1], "warning")
self.assertEqual(
parser.get_items_for_config_file_output(settings, result),
{"level": "warning"},
)
def test_list_element_cannot_end_option_parsing(self):
# otherwise the user's --level would become a positional arg, and the
# config file's level would be used instead of it
for source, kwargs in (
(
"environment",
{
"env_vars": {"ITEMS": '["a", "--"]'},
"config_file_contents": "level = config",
},
),
(
"config",
{"env_vars": {}, "config_file_contents": "items = [a, --]"},
),
(
"environment nested list",
{"env_vars": {"PAIR": '[["a", "--"]]'}},
),
):
with self.subTest(source=source):
parser = configargparse.ArgumentParser()
parser.add_argument("--items", nargs="+", env_var="ITEMS")
parser.add_argument("--pair", nargs=2, action="append", env_var="PAIR")
parser.add_argument("--level")
parser.add_argument("files", nargs="*")
stderr = io.StringIO()
with self.assertRaises(SystemExit), contextlib.redirect_stderr(stderr):
parser.parse_args(["--level", "debug"], **kwargs)
self.assertIn("can't have '--' as a list element", stderr.getvalue())