0

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.

shaoyl85
  • 1,854
  • 18
  • 30
  • Please do not ask, immediately delete, and repost a [question](http://stackoverflow.com/questions/42683687/print-result-if-statement-to-exec-is-an-expression). – TigerhawkT3 Mar 08 '17 at 23:51
  • Thank you @TigerhawkT3! However this is not a duplicate. There isn't an answer in the post you mentioned. – shaoyl85 Mar 09 '17 at 00:20
  • @TigerhawkT3 Would you remove the duplication mark? – shaoyl85 Mar 09 '17 at 00:48

1 Answers1

-1

First of all, executing 10 doesn't make sense in real life. How can you execute a number? But, you can execute a command like exec("print(10)"). I don't see the need of creating a my_exec function. It behaves the same as the normal exec. In the interactive shell, everything works differently, so don't try to compare. Basically, exec("print(10)") is the command you are looking for. Another way not using exec is print(10).

Nairit
  • 161
  • 1
  • 9
  • Thank you! I totally understand that. – shaoyl85 Mar 09 '17 at 00:21
  • For example, the `compile(..., "", "single")` has the behavior of my `my_exec`, but it does not support statements with multiple code blocks which are all executable. – shaoyl85 Mar 09 '17 at 00:51
  • Then, it is possible to use compile instead of my_exec. That was my point. Why go through the hassle when you can use a built in function? – Nairit Mar 09 '17 at 01:39
  • it executes up to the end of the first executable block. for example, `exec(compile("print 42\n print 10", "", "single"))` prints 42 only. my `my_exec` works but it has two compile involved. what i am asking here is indeed a more principled way like you mentioned. – shaoyl85 Mar 09 '17 at 02:22