Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file keyword argument?

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?

like image 937
applecider Avatar asked Nov 24 '15 20:11

applecider


People also ask

What is the keyword argument in Python?

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.

How do you pass a keyword argument in Python?

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)

Does Python support 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.

What is file keyword in Python?

file is neither a keyword nor a builtin in Python 3.


1 Answers

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

like image 162
user1245262 Avatar answered Oct 21 '22 07:10

user1245262