在我正在阅读的Python书籍中,它一直使用代码eval(input('blah'))

我阅读了文档,我理解了它,但我仍然不明白它是如何改变input()函数的。

它能做什么?有人能解释一下吗?


当前回答

如果您想将计算字符串限制为简单的字面量,另一个选项是使用ast.literal_eval()。一些例子:

import ast

# print(ast.literal_eval(''))          # SyntaxError: unexpected EOF while parsing
# print(ast.literal_eval('a'))         # ValueError: malformed node or string
# print(ast.literal_eval('import os')) # SyntaxError: invalid syntax
# print(ast.literal_eval('1+1'))       # 2: but only works due to a quirk in parser
# print(ast.literal_eval('1*1'))       # ValueError: malformed node or string
print(ast.literal_eval("{'a':1}"))     # {'a':1}

从文档中可以看出:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

至于为什么如此有限,从邮件列表中可以看出:

允许使用字面量的运算符表达式是可能的,但是比当前的实现要复杂得多。简单的实现是不安全的:你可以毫不费力地诱导出基本上无限的CPU和内存使用(尝试“9**9**9”或“[None] *9**9”)。 至于实用性,这个函数用于“读回”由repr()字符串化的文字值和容器。例如,可以使用类似于JSON但比JSON更强大的格式进行序列化。

其他回答

eval()函数接受三个参数,求值并返回值。 语法:eval(表达式,全局变量,局部变量) python3表达式的字符串 Globals(可选)#字典 Locals(可选)#字典 #你经常使用的常见用例是 x = "{“名称”:“abhi”,“mydict”:{“子”:python的}}” y=dict(x)print(y,type(y)) # ValueError:字典更新序列元素#0的长度为1;需要2 z = eval (x)打印(z,类型(z)) #{“名称”:“abhi”,“mydict”:{“子”:python的}}<类的dict >

注意eval()和exec()的区别:

>>> exec("x=2")
>>> x
2
>>> eval("x=1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    x=1
     ^

也许是一个阅读一行文字并解释它的误导性例子。

尝试eval(input())并输入“1+1”-这应该打印2。Eval求表达式的值。

eval函数允许Python程序在自身内部运行Python代码。

Eval示例(交互式shell):

>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1

eval()的一个有用的应用是计算python表达式的字符串值。例如load from file string dictionary:

running_params = {"Greeting":"Hello "}
fout = open("params.dat",'w')
fout.write(repr(running_params))
fout.close()

将其作为变量读取并编辑:

fin = open("params.dat",'r')
diction=eval(fin.read())
diction["Greeting"]+="world"
fin.close()
print diction

输出:

{'Greeting': 'Hello world'}