I am using argparse library to parse arguments to my python script. This is my code:
parser = argparse.ArgumentParser(
prog="confgit",
description="Git overhead for version control of your config files",
formatter_class=argparse.RawTextHelpFormatter, )
parser.add_argument(
"-c", "--config",
type=str,
default=DEFAULT_CONFIG_PATH,
dest="CONFIG_PATH",
help="load alternative config")
subparsers = parser.add_subparsers(help="Commands:")
subparsers.add_parser("include", help="Include file or directory in to repository").add_argument(
"file_to_include",
type=str,
action="store",
nargs="?",
const="",
default=False,
help="include file or directory in to repository")
subparsers.add_parser("exclude", help="Exclude file or directory in to repository").add_argument(
"exclude",
type=str,
action="store",
help="exclude file or directory from repository")
print(parser.parse_args())
I would like to be able to store parameters not matching any subparser as a string. For example
running myprogram include test.txt --config .config/cfg.txt will result in:
Namespace(CONFIG_PATH='.config/cfg.txt', file_to_include='test.txt')
and running myprogram some text here will result in:
Namespace(CONFIG_PATH='.config/default.txt', input="some other text")
How can I achieve this ?
Thank you for help
add_subparsersresult to a variable, and then use that with the followingadd_argument. Your chaining works for one argument, but is confusing to this oldargparseuser.