0

For example: I am passing list of item as argument in command prompt following format :

  $test run -list1 ["one day", "one hour"] -list2 ["1234"]

after successful pass list1 and list2 output should be:

 list1: 
      type: list
      output format: ["one day", "one hour"]
 list2:
      type: list
      output formate: ["1234"]
2
  • why don't you just pass a string and use string.split(',') to get the list? Commented Sep 4, 2015 at 10:15
  • Will the command line always be like that, with 2 lists named -list1 and -list2, or can the number of lists and their names vary? Commented Sep 4, 2015 at 10:17

1 Answer 1

2

You can use the argparse module. The syntax will be a little bit different, though.

In your script, you can use the argparse module the following way:

#!/usr/bin/python
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='My awesome script doing stuff')
    parser.add_argument('--list1', metavar='V1', default=[], nargs='+', help='a string for the first list')
    parser.add_argument('--list2', metavar='V2', default=[], nargs='+', help='a string for the second list')

    arguments = parser.parse_args()
    print(arguments.list1)
    print(arguments.list2)

You can then call your script:

$./run.py --list1 "one day" "one hour" --list2 "1234"

You can use nargs='*' instead of nargs='+' to allow for empty lists such as $./run.py --list1 --list2 "something" "something else" instead of forcing omitting the argument name (as in $./run.py --list2 "1234")

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to pass argument as following format: $./run.py --list1 ["one day" "one hour"] --list2 [1234, 5678, 9087]
You won't be able to do so as easily. To start with, this argument sequence will be seen as ['run.py', '--list1', '[one day', 'one hour]', '--list2', '[1234,', '5678,', '9087]'] in sys.argv. You’ll have to add at least quotes or double quotes around the brackets in the command line. Then you’ll be able to retrieve the strings representing the list that you’ll have to convert using ast.literal_eval

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.