Interpreting a Python string as a conditional statement?

前端 未结 2 1074
一整个雨季
一整个雨季 2020-12-11 08:04

I\'m processing some json-formatted log files in python. It\'s very straightforward to code some conditional queries, e.g.

line=[1,\'runtime\',{\'elapsed\':         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-11 08:15

    There is not really a safe way to do that. For basic conditionals you could parse an input string of a specific format. If your input was in the format "var > 5" you could parse it like this:

    var, op, num = argv[1].split()
    var = getattr(sys.modules[__name__], var) # Get a reference to the data
    num = int(num)
    if op == ">":
       r = var > num
    elif op == "<":
       r = var < num
    ...
    
    if r:
        
    

    To support more complicated statements you would need to improve the parser. If you don't trust your input you should wrap the getattr and int in try/except blocks. To support int or float or another var you would need quite a bit of logic.

提交回复
热议问题