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

相关问题