简体   繁体   中英

How does the following code snippet work?

I am a novice in python and am going through an opensource project called pyOBD by Donour Sizemore for the ELM327(not really sure,could be aimed at more scantool devices).I can make out that the following is a method to convert a hex value to int.But how does it work? Specially the line with eval in it.

 def hex_to_int(str):
     i = eval("0x" + str, {}, {})
     return i

eval runs a string as if it were Python code, and then outputs the result.

In this case, it runs something like 0xaf , which is a way of specifying a hexadecimal literal, and outputs the resulting integer. Try typing 0xaf into the Python interpreter, and you'll get an integer as the result.

eval is not safe to use on untrusted input. For example,

eval("0xa and __import__('os').remove('some/file/path')")

could delete a file on your system.

It would be better to use ast.literal_eval or int :

>>> import ast
>>> ast.literal_eval("0xaf")
175
>>> int("af", 16)
175

Which are safe and produce the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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