detect interactivity

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Dec 30 17:29:40 EST 2009


On Wed, 30 Dec 2009 14:42:12 +0100, Vito 'ZeD' De Tullio wrote:

> Steven D'Aprano wrote:
> 
> 
>>> if I run 'python <<< "import sys; print(sys.ps1)"', I get an error.
>> 
>> Of course you do, because you're not running interactively
> 
> Excuse me, why do you say that?

Two reasons.

First, because sys.ps1 is documented as only existing in an interactive 
environment, and sure enough, sys.ps1 fails to exist when you run the 
above.

And secondly, and much more importantly, if you run that command, you do 
not get an interactive prompt.

The format of the command being run is a bash "here string", more-or-less 
equivalent to either of:

echo "import sys; print(sys.ps1)" | python
python -c "import sys; print(sys.ps1)"

both of which also exit with AttributeError.

If you really want to see what's going on, have a look at this:


[steve at sylar ~]$ python -i -c "import sys; print(sys.ps1)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ps1'
>>> sys.ps1
'>>> '


The -c switch tells Python to execute whatever comes next, and the -i 
switch tells Python to enter interactive mode afterwards. At first, 
sys.ps1 does not exist and you get an AttributeError, but then the -i 
switch kicks in, sys.ps1 is defined and you get a prompt.



-- 
Steven



More information about the Python-list mailing list