title: Detect if python script is run from an ipython shell, or run from the command line
body: <p>Is there any way to detect if a python script is being run from an python or ipython shell, or being run from the command line using for example <code>python scrip.py</code>?</p>
  
  <p>I want to use this to set up my matplotlib environment and save or display a figure depending on how the script is run. When I'm running the plotting script from the command line I want the script to use a non-standard matplotlib backend and save the figure to a file with <code>plt.savefig()</code>, but if I'm running it from inside an ipython shell using <code>In [1]: run scrip.py</code>, I want to display the figure using <code>plt.show()</code>.</p>
  
  <p>Something like this:</p>
  
  <pre class="lang-py prettyprint-override"><code>import matplotlib
  if run_from_command_line:
      matplotlib.use("non-standard-backend")
  
  import matplotlib.pyplot as plt
  if run_from_interactive_shell:
      plt.ion() // Turn on interactive mode in matplotlib
  
  // Do plotting
  
  if run_from_command_line:
      plt.savefig(filename)
  else:
      plt.show()
  </code></pre>