python:从命令行输入函数
问题描述:
我目前正在研究一个小的命令行程序,它解析来自网站的电视节目,用户可以调用它的不同功能。我已存储在字典中,看起来像这样的功能:python:从命令行输入函数
commands = {"show": show, "show x": showX, "help": TVhelp, "exit": TVexit,
"actor list": actorList, "actor add x": actorAdd,
"actor delete x": actorDel, "recommend": recommend}
时存储作为该键的值的用户类型任何键,则该函数被调用。例如显示只显示所有程序的列表,帮助和退出应该是自我解释的。
从命令行使用裸函数名称调用这些函数时没有任何问题,但问题是某些函数需要额外的参数(我在此称其为x)。
当用户例如写入“节目20”时,应该显示具有索引20的节目列表中的节目。或者当输入是“演员添加阿诺德施瓦辛格”时,该名字应该添加到列表中。
我想要的是,该函数可以从命令行调用一个额外的参数,程序识别输入中的函数名称并将数字或演员名称作为参数。
有没有用字典做这件事的pythonic方法?
欢呼
答
首先,我建议你使用argparse这一点。该API复杂但有效。
如果你真的想推出你自己的参数解析,只需将任何附加参数传递给字典中指定的函数。
def zoo_desc(args):
y = int(args[2])
describe_me = zoo[y]
print ('{}, {}'.format(describe_me[0], describe_me[1]))
def zoo_list(args):
for index, entry in enumerate(zoo):
print ('{}: {}'.format(index, entry[0]))
handlers = {
'zoo list': zoo_list, # List the animals in the zoo.
'zoo desc': zoo_desc # Describe the indexed animal, aka 'zoo desc x'
}
zoo = [
('cat', 'a cute feline'),
('mouse', 'a cute rodent'),
('rat', 'an uncute rodent')
]
x = input()
while (x):
for a in handlers:
if x.startswith(a):
handlers[a](x.split()) # When we call a handler, we also pass it the arguments
x = input()
输出:
zoo list
0: cat
1: mouse
2: rat
zoo desc 1
mouse, a cute rodent
你只需要做出结构的一些决定,然后执行它们,就像“没有功能键可以有空格”等应有尽有第一空间可以治疗后作为参数列表,例如。 –
不确定你在问什么。你为什么不能在调用函数时通过参数? –
您可以拆分输入文本并检查第一个或两个元素,然后将其余元素作为参数传递给哈希函数 –