Infinite input using argparse
Question
So say I have a merge function. I can merge any number of files into one. This requires a variable number of inputs. So my question is, taking in arguments from argparser, how would I account for the possibility of 2 or more input files?
Solution
You can use either nargs='+'
or nargs='*'
.
These will gather the args into a list.
import argparse
the_parser = argparse.ArgumentParser()
the_parser.add_argument('--input_files',nargs='+')
args = the_parser.parse_args()
If you want to call from another script using subprocess
you could do:
import subprocess
the_files = ['to_merge_1.txt', 'to_merge_2.txt']
cmdlnargs = ['python','argparse_example.py','--input_files']
cmdlnargs.extend(the_files)
subp = subprocess.Popen(cmdlnargs,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = subp.communicate()
print stdout
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow