I am trying to take multiple files as input from terminal. the input number may vary from atleast 1 to many. Here is the input for my program
F3.py -e <Energy cutoff> -i <inputfiles>
I want the parameter -i to take any number of values from 1 to multiple.e.g.
F3.py -e <Energy cutoff> -i file1 file2
F3.py -e <Energy cutoff> -i *.pdb
Right now it takes only the first file and then stops. This is what I have so far:
def main(argv):
try:
opts,args=getopt.getopt(argv,"he:i:")
for opt,arg in opts:
if opt=="-h":
print 'F3.py -e <Energy cutoff> -i <inputfiles>'
sys.exit()
elif opt == "-e":
E_Cut=float(arg)
print 'minimum energy=',E_Cut
elif opt == "-i":
files.append(arg)
print files
funtction(files)
except getopt.GetoptError:
print 'F3.py -e <Energy cutoff> -i <inputfiles>'
sys.exit(2)
Any help would be appreciated. Thanks
Try using the @larsks suggestion, the next snippet should work for your use case:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help='Input values', nargs='+', required=True)
args = parser.parse_args()
print args
kwargs explanation:
nargs
allows you to parse the values as a list, so you can iterate over using something like: for i in args.input
.required
makes this argument mandatory, so you must add at least one elementBy using the argparse module you also got the -h option to describe your params. So try using:
$ python P3.py -h
usage: a.py [-h] -i INPUT [INPUT ...]
optional arguments:
-h, --help show this help message and exit
-i INPUT [INPUT ...], --input INPUT [INPUT ...]
Input values
$ python P3.py -i file1 file2 filen
Namespace(input=['file1', 'file2', 'filen'])