Learn a little lesson a minute

Both Eval and ast.literal_eval can restore a string to the data type to which it can be converted, for example

>>> from ast import literal_eval
>>> 
>>> data1 = "['ops-coffee','cn']"
>>> data2 = "{'title':' operation cafe ','url':'https://ops-coffee.cn'} '"
>>> 
>>> print(type(data1),type(data2))
<class 'str'> <class 'str'>
>>> 
>>> 
>>> 
>>> a1 = eval(data1)
>>> print(a1, type(a1))
['ops-coffee'.'cn'] <class 'list'>
>>> 
>>> a2 = eval(data2)
>>> print(a2, type(a2))
{'title': Operation coffee Bar.'url': 'https://ops-coffee.cn'} <class 'dict'>
>>> 
>>> 
>>> 
>>> b1 = literal_eval(data1)
>>> print(b1, type(b1))
['ops-coffee'.'cn'] <class 'list'>
>>> 
>>> b2 = literal_eval(data2)
>>> print(b2, type(b2))
{'title': Operation coffee Bar.'url': 'https://ops-coffee.cn'} <class 'dict'>
>>> 
>>> 
Copy the code

In addition to converting data types, they can also manipulate string input, for example

>>> eval('1 + 1')
2
>>> 
>>> 
>>> literal_eval('1 + 1'2)Copy the code

So how are they different?

Eval will process any string it can parse, and literal_eval will determine whether the object being processed is a valid Python type, if so, and not otherwise

For example, in the following example

>>> std = input('please input: ')
please input: __import__('os').system('ls /') > > >print('out: '.eval(std))
bin  boot  dev  etc lib lost+found  opt  proc  root  run  sbin  selinux  srv	static	sys  tmp  usr  var
out:  0
>>> 
Copy the code

Eval processes the input instruction, which can be very dangerous. In this case, an LS check is used for testing. If it is an RM or other instruction, the result will be serious

>>> 
>>> print('out: ',literal_eval(std))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/ usr/local/lib/python3.6 / ast py." ", line 85, in literal_eval
    return _convert(node_or_string)
  File "/ usr/local/lib/python3.6 / ast py." ", line 84, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Call object at 0x7f3b192a24a8>
>>> 
Copy the code

Therefore, using Literal_eval greatly reduces system risk and provides a safer performance

Related articles recommended reading:

  • Source code to you, zero base to build a free website navigation station
  • Artifact recommendation | office sedentary you don’t miss the artifact
  • Github Pages accessing too slowly? Free acceleration via Netlify