【发布时间】:2012-07-16 07:13:50
【问题描述】:
我被要求用 Python 模拟 CLI。
这就是我所做的
def somefunction(a,b):
//codes here
//consider some other functions too
print "--- StackOverFlow Shell ---"
while True:
user_input = raw_input("#> ")
splitit = user_input.split(" ")
if splitit[0] == "add":
firstNum = splitit[1]
sNum = splitit[2]
result = somefunction(firstNum, sNum)
print result
//consider some other elif blocks with "sub", "div", etc
else:
print "Invalid Command"
我也会检查列表的长度,这里“拆分”我将只允许 3 个参数,第一个是操作,第二个和第三个是执行某些函数的参数,以防参数大于 3,为此我做了检查。
虽然我设法让它发挥作用,但有没有更好的方法来达到同样的效果?
【问题讨论】:
-
如果要超过 10 个命令,如果您将自己的语法与解析和逻辑“按命令”混合使用,您很快就会陷入困境,并且 shell 将变得无法维护。将其拆分为标记器、解析器(带有一些命令数据库)和解释器(执行单元),这是一个管道,原始输入在执行之前通过这些步骤,而不是为每个命令重复相同的步骤。
-
是的,对于 2-3 个函数,我很好......但我被要求在初始化时不要传递参数。 like myProgram.py
标签: python command-line-interface