1

主文件

import engine
engine.objects['key'] = "It's a key"
engine.main()

引擎.py

# inventory = []

objects = {

}

def main():
    while True:
        choice = raw_input(">>: ")
        command, obj = choice.split()
        if command == 'examine':
            if obj in objects:
                print objects[obj]
            else:
                print 'joking right?'
        else:
            print 'joking right?'

当我键入没有第二个单词的“检查”参数时,它给了我一个错误。

>>: asdf
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    engine.main()
  File "C:\Users\Patrick\Documents\Programming\Game engine test\engine.py", line
 11, in main
    command, obj = choice.split()
ValueError: need more than 1 value to unpack
Press any key to continue . . .

我明白为什么,但我该如何解决呢?

4

2 回答 2

3

所以我们可以raw_input()从问题中消除,并将其归结为以下几行:

choice = 'examine'
result = choice.split()      # result == ['examine']
command, obj = result        # Boom.

from 的返回值split()是一个列表。当您只有一个单词(以空格分隔)时,例如“examine”,列表仅包含一个元素。

然后,当您尝试将该列表解压缩到commandandobj时,python 说:“我不能这样做。您期望两个条目,但我只有一个。”

您需要做的是执行一些中间检查:

args = choice.split()
if len(args) < 2:
    print 'Invalid command.'
    continue
command, obj = args
# ...
于 2012-08-03T02:15:20.010 回答
0
args = choice.split()
command = args[0]
#Branch according to command here
#Most likely you will want to separate them into functions
if command == 'examine':
    if len(args) < 2:
       print 'Missing argument'
    else:
       obj = args[1]
       if obj in objects:
           print objects[obj]
       else:
           print 'joking right?'
else:
    print 'joking right?'

您还可以查看cmdpython 标准库中的模块。您基本上可以使用do_<MYCOMMANDNAME>函数创建一个对象,它会发出命令提示符并将第一个单词视为 acommand并查找相应的do_command函数以使用其余参数执行。

于 2012-08-03T02:35:50.980 回答