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?
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols: *args (Non Keyword Arguments) **kwargs (Keyword Arguments)
Python Keyword ArgumentsPython allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result.
file is neither a keyword nor a builtin in Python 3.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With