我對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')來解決你遇到的問題。打印(一)' –
嗨凱爾,我已經將它添加到問題。謝謝! –