Adding code and methods to a class dynamically



I have a class (Command) that derives from cmd.Cmd and I want to add
methods to it dynamically. I've added a do_alias() method and it would
be nice if I could turn an alias command into a real method of Command
(that way the user could get help and name completion). The code would
be generated dynamically from what gets passed to the do_alias()
method. I've tried looking in the Python cookbook and have tried:

def funcToMethod(func, clas, method_name=None):
setattr(clas, method_name or func.__name__, func)

class Command(object, cmd.Cmd):
# ...
def do_f1(self, rest): print 'In Command.do_f1()'
def do_alias(self, rest):
rest.strip() # remove leading and trailing whitespace
pat = re.compile(r'^(\w+)\s+(\w+)$')
mo = pat.search(rest)
if mo:
newName = mo.group(1)
existingName = mo.group(2)
code = 'def do_' + newName + '(self, rest):\n'
code += ' self.do_' + existingName + '(rest)\n'
exec code
funcToMethod(getattr(newModule, 'do_' + existingName),
self,
'do_' + 'existingName')
else:
print 'Invalid alias command'

but this does not seem to work. What I get is:

$ importDynamic.py
(Cmd) do alias x f1
*** Unknown syntax: do alias x f1
(Cmd)

Any suggestions? Thanks.

Sarir
.



Relevant Pages

  • Re: A clean way to program an interface
    ... using some form of serial communication. ... with his naming of certain methods with the same name as the command ... def makeStatusCheckCommandFunction: ... the command strings are just passed along as the argument cmd, ...
    (comp.lang.python)
  • Re: How To Execute Batch File Line By Line
    ... COMMAND /C string Carries out the command specified by string, ... CMD /C Carries out the command specified by string and then terminates. ... .cmd files will NOT work on non Windows NT versions i.e. Windows 9x, ... Both .cmd and .bat files work on Windows NT versions. ...
    (microsoft.public.windowsxp.general)
  • Re: Command.Com - Sinn und Unsinn?
    ... Kompatibilität für 16-Bit-Porgs dient, dann gilt das auch ... Anforderung die ich an CMD / Command stelle! ... Ich habe seit DOS 4 "Fachwissen" um DOS - und wenn ich ...
    (microsoft.public.de.german.windowsxp.sonstiges)
  • Re: MSinfo32.exe help
    ... when i do the cmd for rd packagestore /s /q(system cant find file ... use it even though i have to use cmd to open it.this bothers me alot i defrag ... my packagestore folder didn't have any .cab files in it ... > command in case there's a problem with word wrap. ...
    (microsoft.public.windowsxp.general)
  • Re: A clean way to program an interface
    ... Yes - You are correct UnidenConnection is nothing more than a pyserial ... with his naming of certain methods with the same name as the command ... def makeStatusCheckCommandFunction: ... the command strings are just passed along as the argument cmd, ...
    (comp.lang.python)