I m making a irc bot https://github.com/mouuff/MouBot
I would like the bot to reply the eval()
when the message starts with !math
but its creating failures if the user enter something like !math exit() and stuff like that
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Use the language services to compile it into an AST, walk the AST making sure that it contains only whitelisted node sets, then execute it.
Example implementation courtesy of unutbu
The issue with
eval()
is that when it is executed, it is valid python code, and theexit()
is a valid part of python code, which usually exit's a program (although this specific function should be used in IDLE, andsys.exit()
is preffered in non-idle use).For this reason,
eval()
should only be used with trusted input, or you should implement a parser for the commands passed to theeval()
function, as to elliminate undesirable input (possibly take a look at theshlex
module for theirsplit()
function if you wish to implement your own, I have used it for many parsers).I am not sure it could help you but look at this -> http://doc.pypy.org/en/latest/sandbox.html
or this -> Is there an alternative to rexec for Python sandboxing?
Don't.
It looks like you are trying to create a math parser. Then use a math parser, not a full-fledged I-will-run-any-code-parser. If you are using *nix, you could use a program like
bc
to do what you want.If you want simple math evaluation why you want to bring whole might of Python behind it, which can and will be abused.
Use something like PyParsing to write a simple calculator e.g. see SimpleCalc.py or fournfn.py , I think those would be enough to get you started. You can also try SimpleParse
and if you DO want to provide eval like powerful and abusable feature, you should start a VM, in which start server processes which will reply to eval queries, and also limit each process using cgroups, when VM goes down start another one or keep a pool of VM and eval processes.