How to tell if I'm being run from a shell or a module

Chris cwitts at
Thu Feb 14 19:01:49 CET 2008

On Feb 14, 7:21 pm, at wrote:
> Hi all,
> Is there any standard way to tell if the user is running from a module
> or from an interactive shell like IDLE or IPython? The best I've come
> up with so far is for a function to look at
> getouterframes(currentframe())[1][1] (the filename in the frame record
> of the frame that called the function), and check if it exists or not
> with os.path.exists. IPython gives '(ipython console)' and IDLE gives
> 'pyshell#0' whereas running from a module gives its filename. This
> seems a bit hacky. Any better ideas?
> --
> Dan Goodman

If you're just trying to prevent some actions from happening if
something loads your script as a module just put the 'action items'
under an if like:
if __name__ == '__main__':

All your functions inside the file will remain in-tact but it won't
execute anything.

More information about the Python-list mailing list