Reputation: 7974
My app written in Python/PySide is going to be customizable with user defined scripts. Sometimes users can enter just an expression returning a value, sometimes a whole script (i.e. mutliple statements, in python often called "suite"). I do not know which of these two options he/she is going to choose. Whatever the user enters, it will be stored in a string which in turn will be parsed and executed.
Is there any easy way to check if a a string contains a python expression or suite? I know there are parser.expr()
or parser.suite()
or compile(,,'expr')
or compile(,,'eval')
functions but for these I need to know ahead if I am going to parse/compile an expression or suite.
I could put the parsing operation into try/except and try both (if one of the passes then it is the right one) but this seems to me as not a viable solution because user script can contain any other syntax error and the try/except can mess this errors into my expression/suite decision logic.
Another way is to 'preparse' the string myself checking if it contains semicolons or newline characters (outsite of strings or comments, of course), indicating it is a suite, but I am not sure if this is robust enough.
Is there any other simpler way to distinguish between expression or suite stored in a string?
Upvotes: 0
Views: 207
Reputation: 59426
Since any expression is a valid suite but not all suites are valid expressions, I'd say you should try to eval
the string as an expressions and if that fails, consider exec
uting it as a suite:
try:
resultValue = eval(text)
except Exception as evalProblem:
try:
exec(text)
except Exception as execProblem:
print "Problems during eval (%s) and during exec (%s)." % (
evalProblem, execProblem)
else:
print "Result of eval was:", resultValue
I see no problem as you fear to run into concerning the "messing up" of your surrounding logic. Of course, every time you execute code the user provides, the user can mess up your things (consider strings containing os.delete('/path/to/my/important/file')
). But unless this is done deliberately, a mere error will not "mess up" anything.
Upvotes: 2