Can I check if I'm running from the interpreter prompt?

S

skip

Is there a reliable way (this is on Solaris if that matters) to tell if I'm
running in the interactive interpreter as opposed to in a script? I think
examining sys.argv works, but wanted to double check.

Thx,

Skip
 
S

skip

Peter> hasattr(sys, "ps1")

Thanks. I wasn't aware there was a documented way to check for
interactivity. It would have been more obvious if sys had an
"isinteractive" method or attribute.
 
A

alex23

Thanks.  I wasn't aware there was a documented way to check for
interactivity.  

That's more of a side-effect than the actual intent of those
attributes, which are there to hold the interpreter prompts. But it
does seem to be the only way.

It might be worth noting that this -doesn't- hold true for iPython:

IPython 0.9.1 -- An enhanced Interactive Python.
[...]
In [1]: import sys
In [2]: hasattr(sys, 'ps1')
Out[2]: False
It would have been more obvious if sys had an
"isinteractive" method or attribute.

You could add the following to your sitecustomize.py:

sys.isinteractive = hasattr(sys, 'ps1')

If you want to check for iPython as well:

sys.isinteractive = hasattr(sys, 'ps1') or hasattr(sys,
'ipcompleter')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top