python - How does the following code snippet work? -


i novice in python , going through opensource project called pyobd donour sizemore elm327(not sure,could aimed @ more scantool devices).i can make out following method convert hex value int.but how work? specially line eval in it.

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

eval runs string if python code, , outputs result.

in case, runs 0xaf, way of specifying hexadecimal literal, , outputs resulting integer. try typing 0xaf python interpreter, , you'll integer result.

eval not safe use on untrusted input. example,

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

could delete file on system.

it better use ast.literal_eval or int:

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

which safe , produce same result.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -