我对 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