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

2024-09-29 22:21:37 发布

您现在位置: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()函数。它可以很好地运行我在脚本中定义的函数,但由于某些原因,它不能真正执行所有代码。我不明白它的逻辑。我得到:

^{pr2}$

谁能帮忙吗?在

谢谢,
古尔


嗨,凯尔

代码如下:

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  

Tags: the函数代码selfre脚本helloif
1条回答
网友
1楼 · 发布于 2024-09-29 22:21:37

看起来您正在尝试构建一个定制的pythonshell。像普通的交互式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中被偷走。)

现在,我们开始吧,好吗?在

^{pr2}$

相关问题 更多 >

    热门问题