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

dg.google.groups at thesamovar.net dg.google.groups at thesamovar.net
Thu Feb 14 16:09:10 EST 2008


Thanks for the replies, but it's not what I meant. What I want to be
able to determine is whether or not the user is running from an
interactive shell (like IPython or IDLE). Checking if
__name__=='__main__' checks if the current module is the one being
run, but suppose you have two modules A and B, with the function f
defined in module B that should print 'Interactive' or 'Module' say.
The module A just consists of: import B; B.f(). Now whenever f is
called, __name__ will not be '__main__' for it. Someone using IDLE
could write import B then B.f() too. The question is: is there a way
for f to determine if someone was using an interactive shell to call
it or if it was being called some other way. The way I came up with
works in these limited cases but won't work in a more general
situation (but perhaps there is no way for it to know in the more
general situation).

Dan

On Feb 14, 7:01 pm, Chris <cwi... at gmail.com> wrote:
> 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__':
>     do_the_cool_stuff()
>
> All your functions inside the file will remain in-tact but it won't
> execute anything.




More information about the Python-list mailing list