In python, if I exec
a statement which prints a value, I will see the output, e.g., exec("print 10")
gives me output 10. However, if I do exec("10")
I got nothing as output, where as if I type 10 in the interactive shell I got 10 as output. How do I get this output when using exec
? That is if the statement to be executed is an expression, I print its result.
My question is how I can decide whether the statement to execute is an expression. Am I supposed to do the following:
def my_exec(script):
try:
print eval(compile(script, '<string>', 'eval'))
except SyntaxError:
exec(script)
# Prints 10.
my_exec("print(10)")
# Prints 10 as well.
my_exec("10")
UPDATE:
Basically I want the behavior of executing a cell in a jupyter notebook.