I have a need in Python to create a list of arguments dynamically. I've created a script to demonstrate this, named args.py, shown below:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-args_file', default = 'args.txt')
with open(parser.parse_args().args_file, 'r') as f:
args = f.readlines()
for arg in args:
parser.add_argument('-' + arg.strip())
dynamic_args = parser.parse_args()
print dynamic_args
I also have a text file in the same folder, named args.txt, also shown below:
arg1
arg2
arg3
As expected, running args.py with no arguments results in:
Namespace(arg1=None, arg2=None, arg3=None, args_file='args.txt')
However, what I'm having trouble with is running my script with the -h argument. I would like the help to display the arguments found in the args_file, as seen in the example below:
usage: args.py [-h] [-args_file ARGS_FILE] [-arg1 ARG1] [-arg2 ARG2]
[-arg3 ARG3]
What I'm seeing instead is:
usage: args.py [-h] [-args_file ARGS_FILE]
Moreover, if I run the script interactively (i.e. python -i arg.py), and at the interactive prompt type the command "parser.print_usage()", I get the wanted response (showing the -argN arguments). Also, typing "arg.py -arg1 1" or "arg.py arg1 1" result in "unrecognized arguments".
I've tried everything I can think of, but I've been unsuccessful thus far. Do any of the Python aficionados have any suggestions?
parse_args(), where the additional options have not yet been set.-hduring the firstparse_args()call..args = f.readlines()thenfor arg in args:. Thatfis already an iterable of lines; just dofor arg in f:and you'll get the same thing (but simpler, briefer, and more efficient).