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()
In short – An Expression always evaluates to a value. And, A statement does something, like creating a variable or displaying a value, it only does whatever the statement says.
Python Expressions: For example any string is also an expressions since it represents the value of the string as well. Python has some advanced constructs through which you can represent values and hence these constructs are also called expressions.
In programming language terminology, an “expression” is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything.
Python's eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you're trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With