using input(), raw_input() to allow user to run different functions
rhvonlehe at gmail.com
rhvonlehe at gmail.com
Tue Jun 30 12:01:31 EDT 2009
On Jun 29, 5:22 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
> rhvonl... at gmail.com wrote:
> > Something's been giving me difficulty..
>
> > We have a USB-attached device that we frequently debug with simple
> > python scripts. The model has always been that each script logs on to
> > the device, does something, then logs off. As it turns out, we have
> > mostly written scripts as unit tests for each API command. So, we'll
> > call one script that will configure a process on the device, and a
> > separate script that will retrieve the results of that process.
>
> > The model is changing inside the device such that all settings will be
> > lost when we log off. This means we'll have to merge a bunch of
> > scripts in various ways.
>
> > I thought it would be neat if I could have one master python script do
> > the logon, then allow the user to input the name of a previously-
> > written script he wanted to execute while logged on. Finally, when
> > exiting the master script, the user would logout from the device.
>
> > I'm trying to test this by using input() or raw_input() to get the
> > function the user wants to execute. I'm not having much luck. Here's
> > an example:
>
> > Shell.py:
> > #! /usr/bin/env python
> > from CollectNDResults import *
> > ...
> > request = input('Script shell >>> ')
> > print request
> > exec (request) ## I realize the parentheses are not needed
> > ...
>
> > When I run Shell.py I get this:
>
> > Script shell >>> CollectNDResults
> > <function CollectNDResults at 0x00AA75F0>
> > Traceback (most recent call last):
> > File "./Shell.py", line 35, in ?
> > Shell(sys.argv[1:])
> > File "./Shell.py", line 24, in Shell
> > exec (request)
> > TypeError: exec: arg 1 must be a string, file, or code object
>
> > Is there a good reference for me to figure out how to turn my function
> > name into the code object that I want to execute? Is there a better
> > way to do what I'm trying to do?
>
> >>> def foo():
> print "running foo"
>
> >>> import sys
> >>> func_name = "foo"
> >>> getattr(sys.modules[__name__], func_name)()
> running foo
Excellent replies, both. I'll get a lot of mileage out of this,
thanks!
More information about the Python-list
mailing list