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?
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
Now, if you try:
you will see:
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