我被要求用 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"
我还检查了列表的长度,这里“splitit”我只允许 3 个参数,第一个是操作,第二个和第三个是要执行某些函数的参数,以防参数超过3、为此我做了检查。
虽然我设法让它发挥作用,但有更好的方法来实现同样的目的吗?
使用PythonCMD
Module:
检查以下几页给出的一些示例
http://docs.python.org/library/cmd.html http://docs.python.org/library/cmd.html# 支持面向行的命令解释器
http://www.doughellmann.com/PyMOTW/cmd http://www.doughellmann.com/PyMOTW/cmd- # 创建面向行的命令处理器
prompt
可以设置为每次要求用户输入新命令时打印的字符串。
intro
是在程序开始时打印的“欢迎”消息。
eg:
import cmd
class HelloWorld(cmd.Cmd):
"""Simple command processor example."""
prompt = 'prompt: '
intro = "Simple command processor example."
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)