I have a script that consumes command line arguments and I would like to implement two argument-passing schemes, namely:
To that end I am passing the argument fromfile_prefix_chars
to the ArgumentParser
constructor.
from argparse import ArgumentParser
parser = ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('filename', nargs='?')
parser.add_argument('--foo', nargs='?', default=1)
parser.add_argument('--bar', nargs='?', default=1)
args = parser.parse_args()
print(args)
--foo
2
--bar
2
$ python script.py --foo 3
Namespace(bar=1, filename=None, foo='3')
$ python script.py @args.txt --foo 3
Namespace(bar='2', filename=None, foo='3')
I was expecting that args.filename
would retain the name of the file, but surprinsingly enough it has the value None
instead. I am aware that I could get the file name from sys.argv
through a bit of processing. Is there a cleaner way (ideally an argparse
-based approach) to elicit the name of the arguments file?
Your script.py
, plus the file. I have added the file name to the file itself.
args.txt
--foo
2
--bar
2
testing:
1803:~/mypy$ python3 stack56811067.py --foo 3
Namespace(bar=1, filename=None, foo='3')
1553:~/mypy$ python3 stack56811067.py @args.txt --foo 3
Namespace(bar='2', filename='args.txt', foo='3')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With