3 ms·
I've had a similar problem before. I wanted to add a "!calc" trigger to an IRC bot written in Python. Rather than implement the Shunting Yard Algorithm [0] to
by Sohcahtoa82 2y ago
I've had a similar problem before.
I wanted to add a "!calc" trigger to an IRC bot written in Python. Rather than implement the Shunting Yard Algorithm [0] to make sure PEMDAS was handled correctly, I wanted to use `eval` (With some extra steps with the AST library to make a whitelist of AST nodes to prevent code injection), but with Python supporting essentially infinite integer precision, someone writing "!calc 9 * 9 * 9 * 9 * 9 * 9 * [..]" would eat up my entire CPU.
I solved it the same way. I execute it in a separate process and terminate it if it takes more than a couple seconds.
[0] https://en.wikipedia.org/wiki/Shunting_yard_algorithm https://en.wikipedia.org/wiki/Shunting_yard_algorithm