用python模拟CLI Shell [英] Simulating CLI Shell with python
问题描述
我被要求用Python模拟CLI。
I was asked to simulate CLI with Python.
这就是我所做的
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,为此我放了一个检查。
I do also check the length of the list, here "splitit" I will allow only 3 argumets, first will be the operation, and second and third are the arguments with which some functions are to be performed, in case the argument is more than 3, for that i do put a check.
尽管我设法以某种方式使它起作用,但是有没有更好的方法来实现相同的目的?
Though Somehow I manage to make it work, but is there a better way to achieve the same?
推荐答案
使用python CMD
模块:
Use python CMD
Module:
请检查以下页面上提供的一些示例
Check few examples given on the below pages
http://docs.python.org/library/cmd.html #支持面向行的命令解释器
http://docs.python.org/library/cmd.html # Support for line-oriented command interpreters
http://www.doughellmann.com/PyMOTW/cmd -#创建面向行的命令处理器
http://www.doughellmann.com/PyMOTW/cmd - # Create line-oriented command processors
提示
设置为每次要求用户输入新命令时要打印的字符串。
prompt
can be set to a string to be printed each time the user is asked for a new command.
简介
是程序开始时显示的欢迎消息。
intro
is the "welcome" message printed at the start of the program.
例如:
import cmd
class HelloWorld(cmd.Cmd):
"""Simple command processor example."""
prompt = 'prompt: '
intro = "Simple command processor example."
这篇关于用python模拟CLI Shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!