http://shell.appspot.com/是如何在线执行代码的?

5 投票
2 回答
561 浏览
提问于 2025-04-17 01:13

我正在搭建一个网站,用户可以像在http://shell.appspot.com/http://ideone.com上那样在线编写Python代码。有没有人能帮我一下,告诉我该怎么做呢?

2 个回答

2

我刚开始学习Python,不过希望下面的链接能帮到你实现目标。你可以使用BaseHTTPServer这个库(http://docs.python.org/library/basehttpserver.html)来处理网页请求,同时可以用ipython(http://ipython.org)来在后台执行Python命令。

6

首先,你可以浏览他们的 源代码。主要的文件只有321行!

简单来说,它为每个用户会话保持一个单独的全局字典,然后使用 compileexec 来运行代码并返回结果。

# log and compile the statement up front
try:
  logging.info('Compiling and evaluating:\n%s' % statement)
  compiled = compile(statement, '<string>', 'single')
except:
  self.response.out.write(traceback.format_exc())
  return

还有

  # run!
  old_globals = dict(statement_module.__dict__)
  try:
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    try:
      sys.stdout = self.response.out
      sys.stderr = self.response.out
      exec compiled in statement_module.__dict__
    finally:
      sys.stdout = old_stdout
      sys.stderr = old_stderr
  except:
    self.response.out.write(traceback.format_exc())
    return

补充: 不使用Google App Engine会让事情变得复杂得多。不过你可以看看 pysandbox

撰写回答