[python-win32] How to determine whether program running as service?

David Rushby davidrushby at yahoo.com
Thu Sep 9 00:49:10 CEST 2004


What's the canonical way to programmatically determine whether a
pywin32-based Python program is running as a Windows service or as a
regular process?

This issue arises because Windows services don't have [functional]
standard output streams, so even simple print statements will
eventually cause the service to raise an unhandled exception.  This
typically causes the thread on which the exception arose to die,
leaving the SCM-listener thread still running, but the service useless
from the perspective of its clients.

So, when running as a service, it's necessary to replace sys.stdout and
sys.stderr with streams that redirect to somewhere other than the
[dysfunctional] console--but there are some complications.  For
example, when the program is hosted by PythonService.exe but running in
debug mode (via 'pythonservice -debug the_service_program.py'), the
normal output streams are available, and because the program is being
debugged, it should produce verbose output.

In pre-200 builds of pywin32, one could simply:
------------------------------------------------
try:
    import servicemanager
    needToReplaceStdStreams = not servicemanager.Debugging()
except ImportError:
    needToReplaceStdStreams = True
else:
    needToReplaceStdStreams = False
------------------------------------------------

With build 200 and later, servicemanager can be imported by non-service
processes, so the code above no longer works.

Examining the name of the executable (sys.executable) won't work,
because Python services don't require that PythonService.exe host them
(a py2exe-fied service is a good example of a situation in which one
might not want to use PythonService.exe).

I noticed in the spambayes codebase that Mark Hammond appears to be
implementing a test somewhat similar to this one with code like this:
------------------------------------------------
try:
    win32api.GetConsoleTitle()
except win32api.error:
    # Not a regular process.
else:
    # A regular process.
------------------------------------------------
That test is not suitable for service-or-regular-process detection
purposes because there are many non-service execution contexts that
lack a proper win32 console.  win32api.GetConsoleTitle() fails in all
of the graphical Python shells I've tried--including PythonWin--yet
it's still desirable to print to the standard streams while running in
a graphical shell.

Can anyone advise me?

Thanks.


		
__________________________________
Do you Yahoo!?
Take Yahoo! Mail with you! Get it on your mobile phone.
http://mobile.yahoo.com/maildemo 


More information about the Python-win32 mailing list