I'm pretty new to Python. I'm trying to modify a script so it will run in an infinite loop, will get Python code lines from the console and will execute the Python code lines.

I'm talking about something that can do the following example:

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>  

I've tried using the exec() function. It works well with running the functions I've defined in my script, but it can't really execute all code for some reason. I don't get its logic. I get:

Shell> myconsole.py  
> PredefindFunction ("Hello")  
This is the result of the PredefinedFunction: Hello!!!  
> a=1  
> print a 
...
NameError: name 'a' is not defined  
Shell>  

Can anyone help please?

Thanks,
Gur


Hi Kyle,

Here is the code:

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  
有帮助吗?

解决方案

It looks like you're trying to build a custom Python shell. Like the normal interactive Python interpreter, but with a few predefined functions. The code module can do that for you.

Let's create a shell with a single predefined function:

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

(Code gratefully stolen from this answer.)

Now, let's run it, shall we?

$ 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top