Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass command line arguments contained in a file and retain the name of that file?

I have a script that consumes command line arguments and I would like to implement two argument-passing schemes, namely:

  • Typing the arguments out at the command line.
  • Storing the argument list in a file, and passing the name of this file to the program via the command line.

To that end I am passing the argument fromfile_prefix_chars to the ArgumentParser constructor.

script.py

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)

args.txt

--foo
2
--bar
2

Sample use cases

$ 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?

like image 399
Tonechas Avatar asked Jun 28 '19 17:06

Tonechas


1 Answers

Your script.py, plus the file. I have added the file name to the file itself.

args.txt

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')
like image 176
hpaulj Avatar answered Oct 04 '22 17:10

hpaulj