On Wed, 30 Dec 2009 03:26:20 +0100, Roald de Vries wrote: > On Dec 30, 2009, at 1:52 AM, Steven D'Aprano wrote: >> On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote: >> >>> 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. >> >> Ah, I should have looked more carefully at the docs... >> >> http://docs.python.org/library/sys.html#sys.ps1 >> >> sys.ps1 and sys.ps2 are documented as only existing if you are running >> interactively. > > This doesn't really work. In ipython, sys.ps1 is not defined.
Then ipython is not a valid implementation of Python, since it breaks a promise of the language. You should report this to the ipython people as a serious bug. > But also > if I run 'python <<< "import sys; print(sys.ps1)"', I get an error. Of course you do, because you're not running interactively and so sys.ps1 doesn't exist. You need to check the existence of ps1: try: sys.ps1 except AttributeError: print "Not running interactively." else: print "Running interactively." Alternatively: if hasattr(sys, 'ps1'): print "Running interactively." else: print "Not running interactively." -- Steven -- http://mail.python.org/mailman/listinfo/python-list