简体   繁体   English

exec function 中的覆盖函数

[英]Override functions in exec function

I'm working on a mobile app that can execute Python code easily, and unlike other execution apps I am going to have it run with actual Python.我正在开发一个可以轻松执行 Python 代码的移动应用程序,与其他执行应用程序不同,我将让它与实际的 Python 一起运行。

I'm using a Flask Webserver and requests to accomplish this.我正在使用 Flask 网络服务器并请求完成此操作。

This is my code:这是我的代码:

@app.route('/exec')
def run():
  exec(request.args.get("code"))

I want to override any print statements or output.我想覆盖任何打印语句或 output。 Using the string.replace method and another function wont work because if someone uses code like print("Use the print() function to send output in Python!") this would be problematic, and people may want to use the function name. Using the string.replace method and another function wont work because if someone uses code like print("Use the print() function to send output in Python!") this would be problematic, and people may want to use the function name. I also want to output errors.我也想 output 错误。

For anyone saying this is unsafe, I have properly sandboxed the server, it will reset around every hour and has a backup server.对于任何说这不安全的人,我已经对服务器进行了正确的沙盒化,它会每隔一小时重置一次,并且有一个备份服务器。

There are a few ways to go about this: if you're doing exec from the same process as Flask, the simplest thing to do is call it with a dictionary of "globals" and pass your own print function. go 关于这一点有几种方法:如果您从与 Flask 相同的进程执行exec ,最简单的方法是使用“全局变量”字典调用它并传递您自己的print ZC1C425268E68384F14AB50。 You can also replace sys.out to reroute it to your own sink.您还可以替换sys.out以将其重新路由到您自己的接收器。

Alternatively, you can write a separate script which reads the input code from stdin, then exec s it, and call that script as a subprocess to read from its output directly.或者,您可以编写一个单独的脚本,从标准输入读取输入代码,然后执行它,然后将该脚本作为子进程调用以直接从其exec读取。 That way also allows you to impose stricter limits on the user's code than the Flask code.这种方式还允许您对用户的代码施加比 Flask 代码更严格的限制。

Whichever way you choose, be sure to also handle the case when the user's code raises an exception or falls into an infinite loop (or just takes way too long to run).无论您选择哪种方式,请务必处理用户代码引发异常或陷入无限循环(或运行时间过长)的情况。 The handling of those cases will depend on which approach you take.这些案件的处理将取决于您采取的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM