On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote:

> Dear all,
> 
> Is it possible for a Python script to detect whether it is running
> interactively? It can be useful for e.g. defining functions that are
> only useful in interactive mode.

Check __name__. It's set to '__main__' when running as a (non-
interactive) script, and to the name of the module when imported.

[st...@sylar ~]$ cat interactive.py
print __name__

[st...@sylar ~]$ python interactive.py
__main__
[st...@sylar ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import interactive
interactive
>>>

The only complications are that it doesn't work well with the -i command 
line switch (it still reports that __name__ == '__main__'), and if you 
start an interactive session __name__ is also set to '__main__'.

Sadly, sys.argv doesn't report the switches used, but in Python 2.6 and 
better you can look at sys.flags to see if the -i switch is being used.

http://docs.python.org/library/sys.html#sys.flags


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to