Lily Sharpton Lily Sharpton - 1 year ago 70
Python Question

Python script to take multiple number of arguments from shell

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 -e <Energy cutoff> -i <inputfiles>

I want the parameter -i to take any number of values from 1 to multiple.e.g. -e <Energy cutoff> -i file1 file2 -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):
for opt,arg in opts:
if opt=="-h":
print ' -e <Energy cutoff> -i <inputfiles>'
elif opt == "-e":
print 'minimum energy=',E_Cut
elif opt == "-i":
print files
except getopt.GetoptError:
print ' -e <Energy cutoff> -i <inputfiles>'

Any help would be appreciated. Thanks

Answer Source

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 element

By using the argparse module you also got the -h option to describe your params. So try using:

$ python -h
usage: [-h] -i INPUT [INPUT ...]

optional arguments:
  -h, --help            show this help message and exit
  -i INPUT [INPUT ...], --input INPUT [INPUT ...]
                        Input values

$ python -i file1 file2 filen
Namespace(input=['file1', 'file2', 'filen'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download