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 python scrip.py
?
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 plt.savefig()
, but if I'm running it from inside an ipython shell using In [1]: run scrip.py
, I want to display the figure using plt.show()
.
Something like this:
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()
METHOD 1
When running in IPython there is a global variable set called
__IPYTHON__
. You can just check to see if this exists with:METHOD 2
As this thread points out you can also look for the
get_ipython
function in your script to not only check if you are running from IPython, but also to check what configuration IPython has.METHOD 3
You can also use the inspect module to inspect the stack and find out if you are running from the interactive interpreter etc.
So an example file:
When run from the command line with
python test.py
the output is:When
execfile
'd from the interactive interpreter:When run within IPython: