How do I tell if I'm running under IDLE?

Terry Jan Reedy tjreedy at udel.edu
Sat Apr 6 19:23:00 EDT 2013


On 4/5/2013 5:30 AM, Steven D'Aprano wrote:

> I'm looking for an official way to tell what interpreter (if any) is
> running, or at least a not-too-horrible unofficial way.

The interpreters distributed by PSF identify themselves on startup, as 
least in interactive mode, by displaying a line like "Python 3.3.0+ 
(default, Mar 30 2013, 17:36:11) [MSC v.1600 32 bit (Intel)] on win32"
The version available as sys.version, sys.hexversion, and 
sys._version(). The platform is available as sys.platform. The compiler 
and compile date are not officially available.

But you seem not to be actually asking 'what interpreter is running' but 
'who started the interpreter' and 'is the interpreter i/o connected to a 
text-mode OS console or to a gui program, such as IDLE, more or less 
simulating an OS console.

There is no official way because it should not matter to a running 
program. It is the goal of at least some IDLE developers to make the 
connection to the IDLE shell as transparent as possible to Python code, 
so that it matters as little as possible*. This is one reason for the 
shift from running user code in the same process and interpreter 
instance as Idle to running user code in a separate process with its own 
interpreter instance.

* There are current tracker issues about making this true. We really do 
not want people to have to write conditional code, unless it is to work 
around a console problem if Idle is not being used ;-).

If you have an issue not already covered on the tracker, I am curious 
what it is.

> Googling comes up with a number of hacks for detecting IDLE. Some of them
> are terrible. For example, I can't believe that somebody actually
> suggested this:
>
> if len(sys.modules) > 20:
>      print "running under IDLE"

This is based on the fact that if running in the same process, there are 
a lot more imported modules and if running in a separate process, there 
are at least a few more imported modules to set up the rpc connection. I 
do not know that '20' is particularly reliable, even on startup.

> This one is better, but still not exactly what I consider great:

Why not, if is works for all Idle versions so far? The irreducible 
effect of any non-OS-console environment is to override the normal i/o.

> sys.stdin.__class__.__module__.startswith('idlelib')

'idlelib' in sys.stdin.__class__.__module__' is possibly more future-proof.

> Ideally, I'd like to detect any arbitrary environment such as Spyder,
> IPython, BPython, etc., but will settle for just IDLE.

I expect that looking as sys.stdin in someway should work for all.

--
Terry Jan Reedy





More information about the Python-list mailing list