Python cmd module - calculating values ​​from a string

I am working on a fast python script with a module cmdthat will allow the user to enter text commands, followed by parameters in the base url query string format. Something like

commandname foo=bar&baz=brack

Using cmd, I can't find which method to override to affect how the argument lineis passed to all methods do_*. I want to run urlparse.parse_qsfor these values, and calling this line by line in each method do_*seems awkward.

The method precmdgets the whole line before it is commandnamesplit and interpreted, so this will not work for my purposes. I am also not very familiar with how to place a decorator inside such a class and could not remove it without violating the scope.

Basically, python docs for cmd say the following

Repeatedly issue an invitation, accept input, analyze the initial prefix of the received input and methods for sending to action, passing them the rest of the string as an argument.

I want to create a method that will perform additional processing for this "remainder of the string" and pass this generated dictionary to the member functions as an argument line, and not interpret them in each function.

Thank!

+3
1

onecmd(), . onecmd() , , cmd.py, urlparse.parse_qs() .

import cmd
import urlparse

class myCmd(cmd.Cmd):
    def onecmd(self, line):
        """Mostly ripped from Python cmd.py"""
        cmd, arg, line = self.parseline(line)
        arg = urlparse.parse_qs(arg) # <- added line
        if not line:
            return self.emptyline()
        if cmd is None:
            return self.default(line)
        self.lastcmd = line
        if cmd == '':
            return self.default(line)
        else:
            try:
                func = getattr(self, 'do_' + cmd)
            except AttributeError:
                return self.default(line)
            return func(arg)

    def do_foo(self, arg)
        print arg

my_cmd = myCmd()
my_cmd.cmdloop()

:

(Cmd) foo
{}
(Cmd) foo a b c
{}
(Cmd) foo a=b&c=d
{'a': ['b'], 'c': ['d']}

, ?

, cmd.Cmd do_* :

import cmd
import urlparse
import types

# function decorator to add parse_qs to individual functions
def parse_qs_f(f):
    def f2(self, arg):
        return f(self, urlparse.parse_qs(arg))
    return f2

# class decorator to iterate over all attributes of a class and apply
# the parse_qs_f decorator to all do_* methods
def parse_qs(cls):
    for attr_name in dir(cls):
        attr = getattr(cls, attr_name)
        if attr_name.startswith('do_') and type(attr) == types.MethodType:
            setattr(cls, attr_name, parse_qs_f(attr))
    return cls

@parse_qs
class myCmd(cmd.Cmd):
    def do_foo(self, args):
        print args

my_cmd = myCmd()
my_cmd.cmdloop()

, , , , , , .

+3

All Articles