We know how to generate Win32 Services Installer with Native Win32 C++ Code, but if we want to do it in Python, how?

We can use Python to generate Win32 services by using py2exe and Python Win32 Extensions.

Here we show the basic steps.

1. Use py2exe to Compile Python Script into EXE

For example, if you want to compile hello.py into exe file, just use following command:

python hello.py py2exe

2. create a Windows service script and compile it to Win32 Service

This step is the same as step 1, just need to add Windows Service Wrapper code in Python script.

Copy the code and put into files, and use step1 command to compile the file.

After the compilation, you will get a service_launcher.exe under folder ./dist and you can install the service from there.

  1. You can use it to install the service on the win32 services list, just run your program with the “-install” parameter and you are done!
  2. Use “-remove” to remove the win32 services. Need to stop the Service before removing the Win32 service.

3. Questions & Answers

  1. While compiling, Why get following error?

         raise ImportError, "No module named " + qname
    

    ImportError: No module named win32com

    We need to install Python Win32 Extensions to compile it.

  2. When you start the service in Windows Control Panel, the service failed. How to check the error and debug?

    please check Windows event log error for details.

  3. Error: can’t load dll

    If your script depends on more third party dlls, you also need to copy the dlls into ./dist folder.

    Or you can add your dll path into System Path. NOTE: The thing you need to do with dll, is to add the path to system path, not just for current user.