0

我对 Python 很陌生。我正在尝试修改脚本,使其在无限循环中运行,从控制台获取 Python 代码行并执行 Python 代码行。

我说的是可以做以下例子的东西:

Shell> myconsole.py  
> PredefindFunction ("Hello")  
This is the result of the PredefinedFunction: Hello!!!  
> a=1  
> if a==1:  
>     print "a=1"  
a=1  
> quit  
Shell>  

我试过使用 exec() 函数。它可以很好地运行我在脚本中定义的函数,但由于某种原因它不能真正执行所有代码。我不明白它的逻辑。我得到:

Shell> myconsole.py  
> PredefindFunction ("Hello")  
This is the result of the PredefinedFunction: Hello!!!  
> a=1  
> print a 
...
NameError: name 'a' is not defined  
Shell>  

有人可以帮忙吗?

谢谢,
古尔


嗨凯尔,

这是代码:

class cParseTermCmd:  
    def __init__(self, line = ""):  
        self.TermPrompt = "t>"  
        self.oTermPrompt = re.compile("t>", re.IGNORECASE)  
        self.TermCmdLine = ""  
        self.line = line  

    # Check if the TermPrompt (t>) exist in line
    def mIsTermCmd (self):
        return self.oTermPrompt.match(self.line)

    # Remove the term prompt from the terminal command line  
    def mParseTermCmd (self):  
        self.TermCmdLine = re.sub(r'%s'%self.TermPrompt, '', self.line, flags=re.IGNORECASE)  
        exec (self.TermCmdLine)  


And I call it in an infinite while loop from:  
def GetCmd (self):  
            line = raw_input('>')  
            self.TermCmdLine = cParseTermCmd(line)  
            if self.TermCmdLine.mIsTermCmd():  
                # Execute terminal command  
                self.TermCmdLine.mParseTermCmd()  
            else:  
                return line  
4

1 回答 1

3

看起来您正在尝试构建自定义 Python shell。像普通的交互式 Python 解释器一样,但有一些预定义的函数。代码模块可以为您做到这一点。

让我们创建一个带有单个预定义函数的 shell:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import readline  # not really required, but allows you to
                 # navigate with your arrow keys
import code


def predefined_function():
    return "whoop!"

vars = globals().copy()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()

(感谢从这个答案中窃取的代码。)

现在,让我们运行它,好吗?

$ python pyshell.py
Python 2.7.5 |Anaconda 1.8.0 (64-bit)| (default, Jul  1 2013, 12:37:52) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> predefined_function()
'whoop!'
>>> a = 1
>>> print (a + 1)
2
于 2014-02-13T07:17:41.923 回答