1

我想构建一个这样的在线 Python shell。目前我正在尝试在 Python 中构建一个模块,它执行以下操作

  1. 创建一个新会话。
  2. 运行作为字符串保存传递的代码并维护当前会话的环境变量。

我正在尝试使用Pysandbox来实现这一点。这是我到目前为止的努力

from sandbox import Sandbox, SandboxConfig
from optparse import OptionParser
import sys,traceback

class Runner:
    def __init__(self):
        self.options = self.parseOptions()
        self.sandbox = Sandbox(self.createConfig())
        self.localvars = dict()
    def parseOptions(self):
        parser = OptionParser(usage="%prog [options]")
        SandboxConfig.createOptparseOptions(parser, default_timeout=None)
        parser.add_option("--debug",
            help="Debug mode",
            action="store_true", default=False)
        parser.add_option("--verbose", "-v",
            help="Verbose mode",
            action="store_true", default=False)
        parser.add_option("--quiet", "-q",
            help="Quiet mode",
            action="store_true", default=False)
        options, argv = parser.parse_args()
        if argv:
            parser.print_help()
            exit(1)
        if options.quiet:
            options.verbose = False
        return options

    def createConfig(self):
        config = SandboxConfig.fromOptparseOptions(self.options)
        config.enable('traceback')
        config.enable('stdin')
        config.enable('stdout')
        config.enable('stderr')
        config.enable('exit')
        config.enable('site')
        config.enable('encodings')
        config._builtins_whitelist.add('compile')
        config.allowModuleSourceCode('code')
        config.allowModule('sys',
            'api_version', 'version', 'hexversion')
        config.allowSafeModule('sys', 'version_info')
        if self.options.debug:
            config.allowModule('sys', '_getframe')
            config.allowSafeModule('_sandbox', '_test_crash')
            config.allowModuleSourceCode('sandbox')
        if not config.cpython_restricted:
            config.allowPath(__file__)
        return config
    def Run(self,code):
        # log and compile the statement up front
        try:
            #logging.info('Compiling and evaluating:\n%s' % statement)
            compiled = compile(code, '<string>', 'single')
        except:
            traceback.print_exc(file=sys.stdout)
            return
        try:
            self.sandbox.execute(code)
        except:
            traceback.print_exc(file=sys.stdout)

def f():
    f = open('test.py')
    code = ''
    for lines in f:
        code = code+lines
    runner = Runner()
    runner.Run('a = 5')
    runner.Run('b = 5')
    runner.Run('print a+b')
f()

我遇到了3个主要问题。

  1. 如何很好地显示错误?例如,运行上面的代码会产生以下输出

    文件“execute.py”,第 60 行,运行 self.sandbox.execute(code) 文件“/home/aaa/aaa/aaa/pysandbox-master/sandbox/sandbox_class.py”,第 90 行,执行返回 self。 execute_subprocess(self, code, globals, locals) 文件“/home/aaa/aaa/aaa/pysandbox-master/sandbox/subprocess_parent.py”,第 119 行,在 execute_subprocess 中引发 output_data['error'] NameError: name 'a'没有定义

这里不受欢迎的是“execute.py”的调用回溯。我只希望函数返回以下错误。

NameError: name 'a' is not defined
  1. 如何维护当前会话的环境?例如,在上面的代码序列中

    a = 5
    b = 5
    打印 a+b

应该会产生输出 10。有什么想法吗?

4

1 回答 1

-1

这应该可以工作,尽管您可能想要使用异常的输出:

from sandbox import Sandbox, SandboxConfig
from optparse import OptionParser
import sys,traceback

class Runner:
    def __init__(self):
        self.options = self.parseOptions()
        self.sandbox = Sandbox(self.createConfig())
        self.localvars = dict()
        self.code = ''
    def parseOptions(self):
        parser = OptionParser(usage="%prog [options]")
        SandboxConfig.createOptparseOptions(parser)#, default_timeout=None)
        parser.add_option("--debug",
            help="Debug mode",
            action="store_true", default=False)
        parser.add_option("--verbose", "-v",
            help="Verbose mode",
            action="store_true", default=False)
        parser.add_option("--quiet", "-q",
            help="Quiet mode",
            action="store_true", default=False)
        options, argv = parser.parse_args()
        if argv:
            parser.print_help()
            exit(1)
        if options.quiet:
            options.verbose = False
        return options

    def createConfig(self):
        config = SandboxConfig.fromOptparseOptions(self.options)
        config.enable('traceback')
        config.enable('stdin')
        config.enable('stdout')
        config.enable('stderr')
        config.enable('exit')
        config.enable('site')
        config.enable('encodings')
        config._builtins_whitelist.add('compile')
        config.allowModuleSourceCode('code')
        config.allowModule('sys',
            'api_version', 'version', 'hexversion')
        config.allowSafeModule('sys', 'version_info')
        if self.options.debug:
            config.allowModule('sys', '_getframe')
            config.allowSafeModule('_sandbox', '_test_crash')
            config.allowModuleSourceCode('sandbox')
        if not config.cpython_restricted:
            config.allowPath(__file__)
        return config
    def Run(self,code):
        code = '\n'.join([self.code,code])
        # log and compile the statement up front
        try:
            #logging.info('Compiling and evaluating:\n%s' % statement)
            compiled = compile(code, '<string>', 'single')
        except:
            traceback.print_exc(file=sys.stdout)
            return
        try:
            self.sandbox.execute(code)
        except:
            err = sys.exc_info()[1]
            print type(err), err
        else:
            self.code = code

def f():
    f = open('test.py')
    code = ''
    for lines in f:
        code = code+lines
    runner = Runner()
    runner.Run('a = 5')
    runner.Run('b = 5')
    runner.Run('print a+b')
f()
于 2012-11-05T18:12:31.890 回答