title: How to properly interpret a single line of python code?
body: <p>I need to execute a line of python code that is entered by the user.
  If it is a statement I want to execute it, but if it is an expression, I want the result to be returned and do some fancy stuff with it.
  The problem is that python has two different functions for that, namely <code>exec</code> and <code>eval</code>.</p>
  
  <p>Currently I just try to evaluate the string that the user entered.
  If that raises a SyntaxError, this may indicate that the string is an statement instead, so I try to execute it.</p>
  
  <pre><code>try:
      result = eval(command, scope)
  except SyntaxError:
      # Probably command is a statement, not an expression
      try:
          exec(command, scope)
      except Exception as e:
          return command + ' : ' + str(e)
  except Exception as e:
      return command + ' : ' + str(e)
  else:
      pass # Some fancy stuff
  </code></pre>
  
  <p>This feels rather hacky. Is there a neater, more pythonic way to do this?</p>