3

I have seen questions about passing in dictionaries and lists to Python using the argparse library. The examples all show what my Python code looks like. But none show me what they look like on the command line. Where do I need braces, brackets, and quotes?

So if I wanted parameters --my_dict and --my_list how would I specify them as called from the command line?

Here is the essence of what I want to accomplish:

Python foo.py --my_dict="{'Name': 'Zara', 'Class': 'First'}" --my_list="['a', 'b', 'c']"
5
  • Read the accepted answer from the following: stackoverflow.com/questions/18608812/… Your dict is actually just a string which you need to parse into a dict Commented Feb 12, 2019 at 18:37
  • Look at sys.argv[1:] to see the list of strings that the shell has passed to your script. You need enough quotes to keep the shell from splitting the strings. Whether you need brackets or braces depends on how you intend to parse the resulting string. The JSON route gives the greatest flexibility. Commented Feb 12, 2019 at 18:40
  • For the list, why not use nargs='+'? Then you can input "--mylist a b c", without added quotes or brackets. Commented Feb 12, 2019 at 18:45
  • Typically, you don't pass raw bits of Python code as an argument. For example, have an option that takes two arguments and is used like --student Zara First, and build the appropriate dict from the resulting tuple. Commented Feb 12, 2019 at 19:07
  • @chepner, make '--student' an `action='append', and use it several times, once for each student. Commented Feb 12, 2019 at 21:07

1 Answer 1

8

You could use ast.literal_eval to safely convert user-inputted strings to Python dicts and lists:

import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument('--my_dict', type=ast.literal_eval)
parser.add_argument('--my_list', type=ast.literal_eval)
args = parser.parse_args()
print(args)

Running

% python script.py --my_dict="{'Name': 'Zara', 'Class': 'First'}" --my_list="['a', 'b', 'c']"

yields

Namespace(my_dict={'Name': 'Zara', 'Class': 'First'}, my_list=['a', 'b', 'c'])
Sign up to request clarification or add additional context in comments.

Comments

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.