在python中使用exec和eval [英] Use of exec and eval in Python

查看:82
本文介绍了在python中使用exec和eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经了解了execeval以及compile的作用.但是,为什么我需要使用它们?我不清楚使用情况.

So I have understood what exec and eval and also compile do. But why would I need to use them? I am being unclear on the usage scenario.

谁能给我一些例子,以便我更好地理解这个概念.因为我知道这全是理论.

Can anyone give me some examples so that I can better appreciate the concept. Cause right I know it is all theory.

推荐答案

我将举一个使用eval的示例,并认为这是最佳选择.

I'll give an example in which I have used eval and where I think it was the best choice.

我正在编写一个简单的软件测试实用程序...用于测试学生练习是否符合作业要求的东西.目的是为简单的配置文件提供一种用作测试规范的方法(解决使用编程语言描述/记录/实现基本编程任务的测试用例的鸡与蛋"问题)

I was writing a simple software testing utility ... something to test whether student exercises were conforming to the assignment requirements. The goal was to provide a way for a simple configuration file to serve as a test specification (to get around a "chicken-and-egg" issue of using a programming language to describe/document/implement the test cases for elementary programming assignments).

我的工具基于标准库中的ConfigParser.但是,我确实希望能够表示任意的Python字符串(包括\ n,\ t的插值,尤其是从中读取的值中任何插值的十六进制编码的ASCII字符.

I based my harness on the ConfigParser in the standard libraries. However, I did want the ability to represent arbitrary Python strings (including interpolations of \n, \t, and especially any interpolated hex encoded ASCII characters in the values read therefrom.

我的解决方案是在parsed_string=eval('''%s''' % cfg_read_item)周围加上try,然后是相同的三重双引号版本("%s"")中的try.

My solution was a try around an parsed_string=eval('''%s''' % cfg_read_item) followed by a try of the triple double-quoted version ("""%s""") of the same.

在这种情况下,替代方案是编写(或找到一个预先编写的)Python语言解析器,并弄清楚如何将其包括在我的程序中并使其适应我的程序.风险很小(我不担心学生提交的代码会欺骗我的解析器,闯入它的监狱而入狱,删除我的所有文件,将我的信用卡号发送给罗马尼亚等等)*

This is a case where the alternative would have been to write (or find a pre-written) Python language parser and figure out how to include and adapt it to my program. The risks are minimal (I'm not worried that student submitted code is going to trick my parser, break out if its jail, delete all my files, send my credit card numbers to Romania and so on)*

*(部分原因是我在Linux上通过不受信任的无头用户帐户对其进行了测试).

*(In part because I was testing them under Linux from an untrusted headless user account).

就像其他人所说的那样,在其他一些用例中,您正在基于输入数据从模板构建代码,并且需要执行该代码(元编程).您应该始终能够以其他方式完成这些任务.但是,只要该替代方法需要进行编码工作,即编写通用的编程语言解析器/编译器/解释器....,那么eval可能是更好的方法.

As here others have said, there are other use cases where you're building code from a template based on input data and need to execute that code (meta programming). You should always be able to accomplish those tasks in another way. However, whenever that alternative entails coding effort that approaches writing a general programming language parser/compiler/interpreter .... then eval may be the better approach.

这篇关于在python中使用exec和eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆