[New-bugs-announce] [issue33227] Cmd do_something only accepts one argument

Oz Tiram report at bugs.python.org
Thu Apr 5 02:26:53 EDT 2018


New submission from Oz Tiram <nahumoz at gmail.com>:

Considering that I want to build an CLI interactive program using cmd.Cmd,
which has multiple functions that accept two or more arguments,
I always have to do parsing of arg inside my do_methods for example:

class Calc(cmd.Cmd):

    do_add(self, arg):
       a, b = parse_ints(arg)
       return a+b

    do_mult(self, arg):
       a, b = parse_ints(arg)
       return a*b

This is easy enough for a simple calculator. But for more logic I need to create more parse_type and explicitly call them at the top of each do_stuff.
Considering this I have created a patch for Cmd.cmd, that keeps the old functionality, but adds the ability to pass multiple arguments without having to parse them every time. 
  
The functionality is as follows:


class MyProg(cmd.Cmd):

    do_simple(self, arg):
       print(arg)

    do_greet(self, name="World")
       print("Hello %s" %s)

    do_add(self, a, b):
       print(a+b)
    

Now in the cmd prompt:

(Cmd) simple foo
foo  
(Cmd) # keeps the old functionallity 
(Cmd) add 2 3
5
# add two properly add the values
(Cmd) add 2
# expects two arguments, so it will print the help for add
(Cmd) greet
Hello World
# does not complain because it has a default value
(Cmd) greet Guido
Hello Guido
(Cmd) greet name=Raymond
Hello Raymond
# works too

None of these example guess the type. It is simply handles as a string. but I am playing around with automatically detecting types of variables using function annotations in python 3.5 and later.

Also, although, not demonstrated here, one can also define:

    def do_some_method_with_kwargs(self, arg1, arg2, **kwargs):
        ... do fancy stuff ...

(Cmd) some_method_with_kwargs foo bar kwargs='{"name": "John", "age"=35}'

kwargs is parsed to a dict (using json.loads) when escaped properly.
This is a bit esoteric, hence not shown here (but the patch patch includes it).
 
I was wondering if this kind of enhancement would be considered for this module? 
I will happily create a PR with tests and documentation explaining this enhanced functionality.

----------
files: cmd.patch
keywords: patch
messages: 314968
nosy: Oz.Tiram
priority: normal
severity: normal
status: open
title: Cmd do_something only accepts one argument
Added file: https://bugs.python.org/file47520/cmd.patch

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33227>
_______________________________________


More information about the New-bugs-announce mailing list