Whi*_*key 2 python command-line-interface
我被要求用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"
Run Code Online (Sandbox Code Playgroud)
我也检查列表的长度,这里"splitit"我将只允许3个参与者,第一个将是操作,第二个和第三个是要执行某些函数的参数,以防参数超过3,为此我做了检查.
虽然不知怎的,我设法让它发挥作用,但有没有更好的方法来实现同样的目标?
ava*_*sal 10
使用python CMD模块:
查看以下页面中给出的几个示例
http://docs.python.org/library/cmd.html#支持面向行的命令解释器
http://www.doughellmann.com/PyMOTW/cmd - #创建面向行的命令处理器
prompt 每次要求用户输入新命令时,都可以设置为要打印的字符串.
intro 是程序开头打印的"欢迎"消息.
例如:
import cmd
class HelloWorld(cmd.Cmd):
"""Simple command processor example."""
prompt = 'prompt: '
intro = "Simple command processor example."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2531 次 |
| 最近记录: |