Calling function from command line

Hans Nowak wurmy at
Wed Sep 18 18:08:58 EDT 2002

> Hi,
> I have a file which includes a working function definition with some 
> inputs and some defaults for those inputs.
> I want to type
> c:\python22\python func1('input1','input2')
> or some such thing and run the function with the inputs I fed it rather 
> than the defaults.  Is such a call possible?

This code may get you started:


def twice(x):
     return 2 * x

def foo(*args):
     print "Yay! You used these arguments:"
     for arg in args:
         print "-", arg

def bar():
     print "bar!"

if __name__ == "__main__":

     import sys, string

     funcname, args = sys.argv[1], sys.argv[2:]

     arglist = string.join(args, ", ")
     cmd = "%s(%s)" % (funcname, arglist)
     print "Executing:", cmd

     result = eval(cmd)

     print "Result:", result


On my box (Win2K with 4NT), I can call it like this:

(P:\test\general) $ twice 4
Executing: twice(4)
Result: 8

(P:\test\general) $ foo "bar" 'bar' 42
Executing: foo(bar, 'bar', 42)
Yay! You used these arguments:
- <function bar at 0x0076A768>
- bar
- 42
Result: None

(P:\test\general) $ bar
Executing: bar()
Result: None

Some people may yell at you or me <wink> because the eval() function is used, 
but as long as it's you who executes the code, it's really no biggie. There may 
be a better way to do this, though, e.g. by inspecting the module's globals and 
locals, and maybe use apply()... Even better may be, just firing up the 
interactive interpreter with your module loaded, and type your function calls 

Hans "so much code so little time" Nowak
The Pythonic Quarter::

More information about the Python-list mailing list