0

我對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 
+0

你可以發佈一些你迄今爲止所做的代碼嗎?我用這兩行'exec('a = 2')來解決你遇到的問題。打印(一)' –

+0

嗨凱爾,我已經將它添加到問題。謝謝! –

回答

2

它看起來像你想建立一個自定義的Python殼。就像普通的交互式Python解釋器一樣,但有一些預定義的功能。 code模塊可以爲你做到這一點。

讓我們創建一個外殼,一個預定義的功能:

#!/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() 

(代碼感激來自this answer被盜。)

現在,讓我們來運行它,好嗎?

$ 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 
+0

謝謝Carsten!這很好!如何返回到我的腳本中的無限循環,以便在用戶在交互模式下輸入了一些命令後,我可以運行其他命令? –

+1

找到了它:CTRL-Z \t 謝謝! –

+0

@GurArie是的,在Windows和Ctrl + D的其他地方應該是Ctrl + Z。但請注意,如果通過寫入'exit()'退出shell,這將不起作用。那隻會結束程序。 – Carsten

相關問題