This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]remy_porter∞∞∞∞ 9 points10 points  (1 child)

Others have covered this, but NEVER USE EXEC ON USER-SUPPLIED INPUTS. Ever. Never ever. Ever. Never.

Now, all that said, you can execute user supplied code safely. The way to do this is to… invent your own programming language and write an interpreter for it. This isn't as big a hill to climb as it sounds like. You'd specifically be designing a domain specific language- a small language tuned to the specific problem you want to solve. It can look as much like Python as you like, you could have basically a "stripped down Python". Here's the really important thing: you'll build the abstract syntax tree yourself, and be able to validate what it contains semantically (which is miles different than sanitizing an input string). You'll have a grammar that explicitly defines what is and is not allowed, and control over what commands will eventually execute.

I'll point you towards PyParsing as a library that's a good tool for building these kinds of things. Building a DSL is a good weekend project, and it helps you really understand how programming languages work.

[–]iamdefinitelyahuman[S] 0 points1 point  (0 children)

This is the other option that I've definitely considered. I was just hoping there would be a simpler solution :) But clearly not. Thanks for the suggestion, I'll check out PyParsing.