【问题标题】:how to pass many arguments through a command function (do_)如何通过命令函数传递许多参数(do_)
【发布时间】:2014-04-26 19:51:50
【问题描述】:

我想编写一个简单的命令,该命令可能需要 3 个参数用于文本冒险游戏。

基本上在提示符下,我会输入“使用钥匙解锁门”,它会运行一个特定的块。

这是我编写的代码,但它不起作用:

def do_use(self, tool, action, object):

    if tool == 'key':
        if action == 'unlock':
            if object == 'door':
                print("seems like it works!")
            else:
                print("nope 1")
        else:
            print("nope 2")
    else:
        print("nope 3")     

注意:其余命令工作正常。我导入了cmd 以下是主要代码:

class Game(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)

    ....


    if __name__ == "__main__":
        g = Game()
        g.cmdloop()

在提示符下,当我输入:

>>> use key unlock door

我收到以下错误消息:

TypeError: do_use() takes exactly 4 arguments (2 given)

如果可以打印,代码就可以工作:

seems like it works!

我们将不胜感激。

【问题讨论】:

  • 似乎有什么问题?你如何判断“它不起作用”?
  • 好问题:好吧,在提示符下,当我键入 >>> 使用钥匙解锁门时,我收到一条错误消息:TypeError: do_use() 需要 4 个参数(给定 2 个)跨度>
  • 你还没有显示什么叫do_use
  • 它是一个内置命令,可与我导入的 cmd 模块一起使用。我有其他命令,如 do_take、do_ask 可以正常工作。您可以在wiki.python.org/moin/CmdModule 找到有关 cmd 模块的更多信息
  • 阅读该文档,看起来所有命令都只接受一个字符串,您必须自己解析字符串。您的命令被定义为采用 4 个参数(包括 self),而 cmd 使用 self, input 调用它,即 2。

标签: python-3.x command-line-arguments


【解决方案1】:

阅读该文档,看起来所有命令都只接收一个字符串,而您必须自己解析该字符串。您的命令被定义为采用 4 个参数(包括 self),而 cmd 使用 self, input 调用它,即 2。我认为可以通过以下方式获得您想要的结果:

def do_use(self, user_input):
    args = user_input.split()
    if len(args) != 3:
        print "*** invalid number of arguments"
    else:
        tool, action, obj = args
 # Do the rest of your code here

【讨论】:

  • 太棒了!我不得不更改一些变量和参数,因为它们是保留关键字。就像“输入和对象”.. 将其更改为“参数,事物”。干得好!
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2012-04-07
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多