1

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?

1

2 Answers 2

0

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
1
0

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']

2
  • Can you be more prolific, perhaps with a script example? I do not how to use what you wrote in order to handle multiple arguments inside the script.
    – Backo
    Apr 15, 2014 at 12:32
  • @Backo Yup. just added
    – heinst
    Apr 15, 2014 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.