如何编写可以获取和执行python命令的python脚本?

时间:2014-02-13 06:58:14

标签: python command-line-interface command-execution python-exec

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

1 个答案:

答案 0 :(得分:3)

看起来您正在尝试构建自定义Python shell。像普通的交互式Python解释器一样,但有一些预定义的函数。 code模块可以为您做到这一点。

让我们创建一个具有单个预定义函数的shell:

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