一个Python的交互式解释器,python解释器,因为在安卓上装的SL4A


因为在安卓上装的SL4A并没有交互式的解释器,因此自己写了一个,并且添加了Logger和Opertor两个对象,分别用于记录用户输入的命令和结果,以及从文件读取代码.Logger的指令记录功能使用前请打开记录开关,即调用Logger.StartLogCommand(),直到关闭记录开关Logger.StopLogCommand()前都可以调用Logger.SaveCommand()来存储所输入的指令.

#coding:cp936import sysimport time#记录员class Logger:    def __init__(self):        self.__lastResult = None        self.__results = []        self.__result_flag = False        self.__commands = []        self.__command_flag = False        self.__command_ignore_flag = False    #最后的结果    def GetLastResult(self):        self.__command_ignore_flag = True        return self.__lastResult    #取得记录的操作结果    def GetResult(self,i):        self.__command_ignore_flag = True        l = len(self.__results)        if i > -l and i < l:            return self.__results[i]        return None    #取得记录结果状态    def ResultState(self):        self.__command_ignore_flag = True        return self.__result_flag    #设置最后操作结果    def SetLastResult(self,r):        self.__lastResult = r        if self.__result_flag:            self.__results.append(r)    #开始记录操作结果    def StartLogResult(self):        self.__result_flag = True        return self.__result_flag    #保存记录的操作结果    def SaveResult(self,path):        fp = open(path,"wt")        fp.write("\\n".join(self.__results))        fp.close()        return path    #暂停记录操作结果    def StopLogResult(self):        self.__result_flag = False        self.__results = []        return self.__result_flag    #取得命令    def GetCommand(self,i):        self.__command_ignore_flag = True        l = len(self.__commands)        if i > -l and i < l:            return self.__commands[i]        return None    #取得命令状态    def CommandState(self):        self.__command_ignore_flag = True        return self.__command_flag    #开始记录命令    def StartLogCommand(self):        self.__command_ignore_flag = True        self.__command_flag = True        return self.__command_flag    #保存命令    def SaveCommand(self,path):        self.__command_ignore_flag = True        fp = open(path,"wt")        fp.write("\\n".join(self.__commands))        fp.close()        return path    #暂停记录命令    def StopLogCommand(self):        self.__command_flag = False        self.__commands = []        return self.__command_flag    #记录新的命令    def AddCommand(self,c):        if self.__command_flag and not self.__command_ignore_flag:            self.__commands.append(c)        self.__command_ignore_flag = False#操作员class Opertor:    def __init__(self):        pass    def Loads(self,path):        try:            fp = open(path,"rt")            cmd = fp.read()            fp.close()            exec(cmd)        except:            info = sys.exc_info()            print info[0]            print info[1]#控制台class Console:    #单行特殊符号    singleLineSpecial = ["print", "global", "return", "raise", "pass", "from", "import"]    #多行特殊符号    multiLineSpecial = ["class", "def", "try", "for", "while", "if"]    def __init__(self):        self.__commands = []        self.__working = False;        self.__logger = Logger()        self.__opertor = Opertor()        self.__endOfMultiline = ""        self.InitSpace()        self.TrunToSingleLine()    #exec执行命令    def Exec(self):        command = "\\n".join(self.__commands)        self.__commands = []        try:            exec(command,self.__space)            self.__logger.AddCommand(command)        except:            info = sys.exc_info()            print info[0]            print info[1]    #eval执行命令    def Eval(self):        command = "\\n".join(self.__commands)        try:            r = eval(command,self.__space)            if r != None:print "= %s" % str(r)            self.__logger.SetLastResult(r)            self.__commands = []            self.__logger.AddCommand(command)        except:            self.Exec()    #获取输入时提示信息    def message(self):        if self.__isSingleline:            return ">>> "        else:            l = self.__line            self.__line += 1            return "%03d:" % l    #读取一行    def ReadLine(self):        command = raw_input(self.message())        return command    #开始运行    def Start(self):        print self.Greet()        self.__working = True        while self.__working:            command = self.ReadLine()            self.Check(command)    #开始运行问候    def Greet(self):        Author = "LYC"        now = time.strftime("%Y-%m-%d %X", time.localtime())        version = sys.version        platform = sys.platform        text = "Hello,I am %s.Now is %s\\n" % (Author, now)        text += "Python %s on %s\\n" % (version, platform)        return text    #退出控制台    def Quit(self):        self.__working = False    #多行命令退出标志    def EndOfLine(self,char = ""):        self.__endOfMultiline = char    #初始化运行空间    def InitSpace(self):        self.__space = {"Author":"LYC", "Quit":self.Quit, "Logger":self.__logger, "Opertor":self.__opertor, "EndLine":self.EndOfLine, "InitSpace":self.InitSpace}    #转为多行命令    def TrunToMultiLine(self):        self.__isSingleline = False        self.__method = self.Exec        self.__line = 2    #转为单行命令    def TrunToSingleLine(self):        self.__isSingleline = True        self.__method = self.Exec        self.__line = 0    #单行命令检查    def CheckSingleLine(self):        command = self.__commands[-1]        if command:            c = command[-1]            if c == "\\\\":self.TrunToMultiLine()            else:                t = ""                for i in command:                    if i.isalpha():t += i                    elif i.isalnum():t += i                    elif i == "_":t += i                    else:break                if t in self.singleLineSpecial:                    self.__method = self.Exec                elif t in self.multiLineSpecial:                    self.TrunToMultiLine()                else:                    self.__method = self.Eval            return self.__isSingleline        else:return True    #多行命令检查    def CheckMultiLine(self):        command = self.__commands[-1]        if command == self.__endOfMultiline:            self.TrunToSingleLine()            return True        else:            return False    #检查命令    def Check(self,command):        command = command.rstrip()        self.__commands.append(command)        if self.__isSingleline:            if self.CheckSingleLine():self.__method()        else:            if self.CheckMultiLine():self.__method()console = Console()try:console.Start()except:    info = sys.exc_info()    print info[0]    print info[1]    input()#该片段来自于http://byrx.net

评论关闭