views:

51

answers:

1

I am developing cli with python version 2.4.3. i want to have the input exception check. The following is part of the code. With this code, I can type

addcd -t 11 

and if I type

addcd -t str_not_int

or

addcd -s 3

I will catch the error of wrong type argument and wrong option. However, it is not sufficient. e.g.

addcd s 11

or

addcd s a 

then the optparse cannot detect this kind of misinput.

to eliminate the case like "addcd s a 11 21", I add something by checking number of argument, but I do not know if it is the right way.

So, how can I implement a thorough/efficient input check for CLI?

class OptionParsingError(RuntimeError):
    def __init__(self, msg):
        self.msg = msg

class OptionParsingExit(Exception):
    def __init__(self, status, msg):
        self.msg = msg
        self.status = status

class ModifiedOptionParser(optparse.OptionParser):
    def error(self, msg):
        raise OptionParsingError(msg)

    def exit(self, status=0, msg=None):
        raise OptionParsingExit(status, msg)

class CDContainerCLI(cmd.Cmd):
    """Simple CLI """
    def __init__(self):
        """ initialization """ 
        cmd.Cmd.__init__(self) 
        self.cdcontainer=None

    def addcd(self, s):
        args=s.split()
        try:
            parser = ModifiedOptionParser()
            parser.add_option("-t", "--track", dest="track_number", type="int",
               help="track number")
            (options, positional_args) = parser.parse_args(args)
        except OptionParsingError, e:
            print 'There was a parsing error: %s' % e.msg
            return
        except OptionParsingExit, e:
            print 'The option parser exited with message %s and result code %s' % (e.msg, e.status)
        return
        if len(args) != 4:
            print "wrong number of inputs"
            return

        cd_obj= CD()
        cd_obj.addCD(options.track_number, options.cd_name)
+2  A: 

First, read this http://docs.python.org/library/optparse.html#terminology.

You're not following the optparse rules for options. If you don't follow the rules, you cannot use this library.

Specifically.

addcd s 11

or

addcd s a 

Are not legal options. No "-". No "--". Why no "-"?

"then it cannot detect."

Cannot detect what? Cannot detect that they're present? Of course not. They're not legal options.

Cannot detect that the option parameters are the right type? Of course not. They're not legal options to begin with.


eliminate the case of "addcd s a 11 21"

Since none of that looks like legal options, then optparse can't help you. Those aren't "options".

Those are "arguments". They will be found in the variable positional_args. However, you're not using that variable. Why not?


Indeed, this code

    return
    if len(args) != 4:
        print "wrong number of inputs"
        return

Makes no sense at all. After return no statement can be executed. Why write code after a return?

Why check the len of args after parsing args? It's already parsed, it's too late to care how long it was.

S.Lott
so you mean optparser cannot check it at all, and I have to make the command syntax check on my own? in case of that, what is the meaning of optparse? since if I have to check the syntax all by myself, I could also check option and argument type, they are just part of it. "return" is to return back to have new input
pepero
@pepero: Please read the optparse rules. Options begin with "-". Your thing about "s 11" and "s a" has no "-". With no "-", they're not legal options. Why do you show examples with no "-"?
S.Lott
Hi, S.Lott, thank you for your comment. I am asking this because I want my cli to be robust. Dummy users can type anything.
pepero
Yes, dummy users type anything they want and you have to handle it. Optparse helps you parse and validate the *options*. Your cases without a leading "-" are not options, those are *arguments* which (obviously) an *option parser* doesnt care about. What a program actually do with its argument is usually (read: always) specific to that program alone and you wont find a library that validates it.
mizipzor
@pepero: "Dummy users can type anything". That's why you (1) produce error messages, (2) supply help and (3) write documentation. You don't try to parse random crap typed by dummy users. You provide help so dummy users type stuff that is proper. Same with English. Only words, in the right order, are English. Random asdkfjn asjd ;akdjshf lkjadsf ;a isn't English.
S.Lott
"error messages", that is what I am asking by this post. how to catch non-option input such as "addcd s 10"?
pepero
@pepero: " how to catch non-option input such as "addcd s 10"". I'll repeat this. "They will be found in the variable positional_args". You have the non-option input `positional_args`. It's in `positional_args`. You already have this non-option information.
S.Lott