interactive test

Tim Peters tim.one at home.com
Wed Jan 31 02:42:04 EST 2001


[mrnolta at my-deja.com]
> What's the appropriate way to test for an
> interactive Python session? Right now I'm using:
>
> 	if sys.path[0] == '':
> 		interactive = 1
>
> which works, but it's often screwed up by people
> mangling the search path.
>
> I tried testing the Py_InteractiveFlag global, but
> that doesn't seem to work.

Py_InteractiveFlag works fine, but it's non-zero only when -i is an argument
to Python (it records whether the Interactive Flag was specified).

Beyond that, Python doesn't really know whether it's in an interactive
session.  It decides whether to run off printing prompts based on whether
its input file appears to be a tty (or doesn't but -i was specified).  A
side effect of that is probably the best handle you've got:  the prompt
(normally ">>> ") is the value of sys.ps1, but that attribute of sys doesn't
get created *unless* Python believes it needs to print a prompt.  So

import sys
if hasattr(sys, "ps1"):
    # probably interactive
else:
    # probably not interactive

You can't be certain with this, though, because there's nothing to stop a
user from creating or destroying sys.ps1 themself.

although-i-have-yet-to-see-someone-do-either-ly y'rs  - tim





More information about the Python-list mailing list