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']"
ChuckZ
  • 330
  • 3
  • 13
  • Read the accepted answer from the following: https://stackoverflow.com/questions/18608812/accepting-a-dictionary-as-an-argument-with-argparse-and-python Your `dict` is actually just a string which you need to parse into a dict – liamhawkins Feb 12 '19 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. – hpaulj Feb 12 '19 at 18:40
  • For the list, why not use `nargs='+'`? Then you can input "--mylist a b c", without added quotes or brackets. – hpaulj Feb 12 '19 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. – chepner Feb 12 '19 at 19:07
  • @chepner, make '--student' an `action='append', and use it several times, once for each student. – hpaulj Feb 12 '19 at 21:07

1 Answers1

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'])
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677