Question

I am new to Python and I would like to run a script by passing a variable number of arguments. That is, from my terminal window I would like to run the same command as-like the followings:

// Case1
python script.py arg
// Case2
python script.py arg1 arg2 arg3 arg3 arg4 ... argN

In Case1 I know how to do that but I don't know how to make the script to handle the case with multiple and variable arguments passed (Case2). How can I?


Bonus: How to document the above behavior through the argparse module?

Was it helpful?

Solution

It's as simple as:

import sys

for arg in sys.argv[2:]:
    print arg

This print all the arguments given from the command line.

If you would like to use argparse, you can do:

import argparse

parser = argparse.ArgumentParser(description='View arguments')
parser.add_argument('arguments', nargs='+', help='passed arguments')
args = parser.parse_args()
print args.arguments

OTHER TIPS

sys.argv[2:] should do what you need it to get all 1 - N input arguments in a list

Edit: Example Code

Here's a quick script:

test.py hi hello test

Code:

import sys
l = sys.argv[2:]
print l

Prints:

['hello', 'test']

If you want to get all the input arguments, you can do:

Code:

import sys
l = sys.argv[1:]
print l

Prints:

['hi', 'hello', 'test']

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top