detect interactivity

Steve Holden steve at holdenweb.com
Tue Dec 29 22:10:22 EST 2009


Roald de Vries wrote:
> 
> On Dec 30, 2009, at 2:28 AM, Dave Angel wrote:
> 
>> Roald de Vries wrote:
>>> On Dec 29, 2009, at 8:34 PM, Dave Angel wrote:
>>>> Antoine Pitrou wrote:
>>>>> Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :
>>>>>
>>>>>
>>>>>> 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.
>>>>>>
>>>>>
>>>>> Try the isatty() method (*) on e.g. stdin:
>>>>>
>>>>> $ python -c "import sys; print sys.stdin.isatty()"
>>>>> True
>>>>> $ echo "" | python -c "import sys; print sys.stdin.isatty()"
>>>>> False
>>>>>
>>>> Your test determines whether input is redirected.  But I think the
>>>> OP was asking how to detect whether the script was being run from an
>>>> interpreter prompt.
>>>
>>> That was my question indeed. Is it possible?
>>>
>>>
>> If I had had a good answer, I would have supplied it in my earlier
>> message.
>>
>> The sneaky answer would be that a script cannot be used interactively,
>> as once you import it from the interpreter, it's a module, not a
>> script.  So you can detect that it's not a script, by examing __name__
>> in the usual way.  If it's a script, it'll have a value of "__main__".
>>
>> But that won't tell you if you're running inside an IDE, or using the
>> -i switch on the Python command line, or probably a bunch of other
>> questions.  I don't know of any "correct" answer, and I'm not sure
>> what the real use case is for knowing.  Are you really going to
>> somehow define a different set of functions???
> 
> I'm using a database, and want to use python interactively to manipulate
> it. On the other hand, I also want to be able to use it
> non-interactively. In that case, it would be a waste of CPU to load the
> function/class definitions meant for interactive use.
> 
This is an extreme case of premature optimization. Write the code and
run it. Do you have any idea how much extra time and memory loading the
additional code will require? If not, it's a waste of your time to even
think about omitting the stuff required for interactive use.

Once you get a handle on the structures and functions required for
interactive vs. non-interactive use you can consider refactoring the
code so that the non-interactive programs don't need to import the stuff
that's exclusively for interactive use. But frankly I wouldn't waste
your time.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list