En Thu, 14 Feb 2008 19:09:10 -0200, <dg**************@thesamovar.net>
escribió:
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).
It depends on what you mean by "an interactive shell"? If you start your
script with:
python -i whatever.py
is it an interactive shell or not?
I tried these two criteria:
a) See if the __main__ module has a __file__ attribute.
b) See if sys.stdin is a real tty
These are the results I got on Windows for several configurations:
<test.py>
import sys
print "__main__ has __file__", hasattr(sys.modules['__main__'], '__file__')
import os
print "sys.stdin is a tty", hasattr(sys.stdin, "fileno") and
os.isatty(sys.stdin.fileno())
</test.py>
python test.py
__main__ has __file__ True
sys.stdin is a tty True
python -i test.py
__main__ has __file__ True
sys.stdin is a tty True
python test.py <nul >nul
__main__ has __file__ True
sys.stdin is a tty True
python test.py <emptyfile >nul
__main__ has __file__ True
sys.stdin is a tty False
pythonw.exe (the consoleless Python executable for Windows)
__main__ has __file__ True
sys.stdin is a tty False
IDLE
__main__ has __file__ False
sys.stdin is a tty False
pythonwin.exe
__main__ has __file__ False
sys.stdin is a tty False
--
Gabriel Genellina