nativePipeTestService.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # This is an example of a service hosted by python.exe rather than
  2. # pythonservice.exe.
  3. # Note that it is very rare that using python.exe is a better option
  4. # than the default pythonservice.exe - the latter has better error handling
  5. # so that if Python itself can't be initialized or there are very early
  6. # import errors, you will get error details written to the event log. When
  7. # using python.exe instead, you are forced to wait for the interpreter startup
  8. # and imports to succeed before you are able to effectively setup your own
  9. # error handling.
  10. # So in short, please make sure you *really* want to do this, otherwise just
  11. # stick with the default.
  12. import sys
  13. import os
  14. import win32serviceutil
  15. import servicemanager
  16. from pipeTestService import TestPipeService
  17. class NativeTestPipeService(TestPipeService):
  18. _svc_name_ = "PyNativePipeTestService"
  19. _svc_display_name_ = "Python Native Pipe Test Service"
  20. _svc_description_ = "Tests Python.exe hosted services"
  21. # tell win32serviceutil we have a custom executable and custom args
  22. # so registration does the right thing.
  23. _exe_name_ = sys.executable
  24. _exe_args_ = '"' + os.path.abspath(sys.argv[0]) + '"'
  25. def main():
  26. if len(sys.argv)==1:
  27. # service must be starting...
  28. # for the sake of debugging etc, we use win32traceutil to see
  29. # any unhandled exceptions and print statements.
  30. import win32traceutil
  31. print("service is starting...")
  32. print("(execute this script with '--help' if that isn't what you want)")
  33. servicemanager.Initialize()
  34. servicemanager.PrepareToHostSingle(NativeTestPipeService)
  35. # Now ask the service manager to fire things up for us...
  36. servicemanager.StartServiceCtrlDispatcher()
  37. print("service done!")
  38. else:
  39. win32serviceutil.HandleCommandLine(NativeTestPipeService)
  40. if __name__=='__main__':
  41. try:
  42. main()
  43. except (SystemExit, KeyboardInterrupt):
  44. raise
  45. except:
  46. print("Something went bad!")
  47. import traceback
  48. traceback.print_exc()