Python file keyword argument?

applecider picture applecider · Nov 24, 2015 · Viewed 8.2k times · Source

In command line I am able to pass arguments to a python file as:

python script.py arg1 arg2

I can than retrieve arg1 and arg2 within script.py as:

import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]

However, I would like to send keyword arguments to a python script, and retrieve them as a dictionary:

python script.py key1=value1 key2=value2

Then I would like to access the keyword arguments as a dictionary within python:

{'key1' : 'value1', 'key2' : 'value2'}

Is this possible?

Answer

user1245262 picture user1245262 · Nov 24, 2015

I think what you're looking for is the argparse module https://docs.python.org/dev/library/argparse.html.

It will allows you to use command line option and argument parsing.

e.g. Assume the following for script.py

import argparse

if __name__ == '__main__':
   parser = argparse.ArgumentParser()
   parser.add_argument('--arg1')
   parser.add_argument('--arg2')
   args = parser.parse_args()

   print args.arg1
   print args.arg2

   my_dict = {'arg1': args.arg1, 'arg2': args.arg2}
   print my_dict

Now, if you try:

  $ python script.py --arg1 3 --arg2 4

you will see:

3
4
{'arg1': '3', 'arg2': '4'}

as output. I think this is what you were after.

But read the documentation, since this is a very watered down example of how to use argparse. For instance the '3' and '4' I passed in are viewed as str's not as integers