Calling function from command line
Hans Nowak
wurmy at earthlink.net
Wed Sep 18 18:08:58 EDT 2002
GREGORY KNESER wrote:
> Hi,
>
> I have a file func.py which includes a working function definition with some
> inputs and some defaults for those inputs.
>
> I want to type
>
> c:\python22\python func.py 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:
---->8----
# cmdline.py
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
---->8-----
On my box (Win2K with 4NT), I can call it like this:
(P:\test\general) $ cmdline.py twice 4
Executing: twice(4)
Result: 8
(P:\test\general) $ cmdline.py 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) $ cmdline.py bar
Executing: bar()
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
there.
--
Hans "so much code so little time" Nowak
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html
More information about the Python-list
mailing list