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

Jeff McNeil jeff at jmcneil.net
Thu Feb 14 12:40:23 EST 2008


Check to see what the value of '__name__' is, for example:

if __name__ == '__main__':
   execute_interactive_code()
else:
   I_am_just_a_lowly_module()

The value of __name__ will correspond to the name of your module:

$ cat a.py
print __name__
$

$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
a
>>>

Thanks!

Jeff

On 2/14/08, dg.google.groups at thesamovar.net <dg.google.groups at thesamovar.net>
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
> http://thesamovar.net/contact
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080214/d4b825f4/attachment-0001.html>


More information about the Python-list mailing list