views:

99

answers:

2

Hello

I need to either call exec() or eval() based on an input string "s"

If "s" was an expression, after calling eval() I want to print the result if the result was not None

If "s" was a statement then simply exec(). If the statement happens to print something then so be it.

s = "1 == 2" # user input
# ---
try:
    v = eval(s)
    print "v->", v
except:
    print "eval failed!"
# ---
try:
    exec(s)
except:
    print "exec failed!"

For example, "s" can be:

s = "print 123"

And in that case, exec() should be used.

Ofcourse, I don't want to try first eval() and if it fails call exec()

+7  A: 

Try to compile it as an expression. If it fails then it must be a statement (or just invalid).

isstatement= False
try:
    code= compile(s, '<stdin>', 'eval')
except SyntaxError:
    isstatement= True
    code= compile(s, '<stdin>', 'exec')

result= None
if isstatement:
    exec s
else:
    result= eval(s)

if result is not None:
    print result
bobince
Good idea, thank you bobince!
lallous
+4  A: 

It sort of sounds like you'd like the user to be able to interact with a Python interpreter from within your script. Python makes it possible through a call to code.interact:

import code    
x=3
code.interact(local=locals())
print(x)

Running the script:

>>> 1==2
False
>>> print 123
123

The intepreter is aware of local variables set in the script:

>>> x
3

The user can also change the value of local variables:

>>> x=4

Pressing Ctrl-d returns flow of control to the script.

>>> 
4        <-- The value of x has been changed.
unutbu
Unfortunately, this is not a feasible option. I provide a simple UI input box for the user to type the string.
lallous