TAGS :Viewed: 5 - Published at: a few seconds ago

[ kwargs in python executables ]

I'm trying to create a program that can be called from the command line and use keyword arguments in python 2.6. So far I've tried:

def read(foo = 5):
    print foo
    return 0
if __name__ == '__main__'

When I try to run this from the command line: ./test.py the program prints 5 as expected. Is there a way to use ./test.py foo=6? I want to preserve the keyword arguments.

It seems like a simple question, but I haven't found a good source for this.

Answer 1

python has built in library to help you achieve passing command line arguments to a script argparse. THe usage is a little different then what you are describing in your question though...

On a basic level you can access all command line arguments by sys.argv, which will be a list of arguments

Sorry should have mentioned the python 2.6 library is called optparse

Answer 2

Something like this?

if __name__ == '__main__':
    kwargs = dict(x.split('=', 1) for x in sys.argv[1:])

That said, argparse and optparse are probably going to give you something more robust and more natural for someone used to the commandline. (Not to mention, supporting arguments of types other than string.)

Oh, and if what you're really after is just interactive use of your function, use the interactive interpreter; either python or ipython. You'd need to put the code into a file ending in .py and import it, then you could just call it.

Answer 3

A less usual, but very interesting alternative is docopt: a library that generates an argument parser from the help message that you write for your program (on github).