I'm doing some work evaluating log data that has been saved as JSON objects to a file. To facilitate my work I have created 2 small python scripts that filter out logged entries according to regular expressions and print out multiple fields from an event.
Now I'd like to be able to evaluate simple mathematical operations when printing fields. This way I could just say something like
./print.py type download/upload
and it would print the type and the upload to download ratio. My problem is that I can't use eval()
because the values are actually inside a dict
.
Is there a simple solution?
eval
optionally takes aglobals
andlocals
dictionaries. You can therefore do this:Keep in mind that
eval
is "evil" because it's not safe if the executed string cannot be trusted. It should be fine for your helper script though.For completness, there's also
ast.literal_eval()
which is safer but it evaluates literals only which means there's no way to give it a dict.You could pass the
dict
toeval()
as thelocals
. That will allow it to resolvedownload
andupload
as names if they are keys in thedict
.