我对Python很新颖。我试图修改一个脚本,使其在无限循环中运行,从控制台获取Python代码行并执行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
你可以发布一些你迄今为止所做的代码吗?我用这两行'exec('a = 2')来解决你遇到的问题。打印(一)' –
嗨凯尔,我已经将它添加到问题。谢谢! –