Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Windows Service with Python 3.5 and pyinstaller

TestService

Windows Service with Python 3.5 and pyinstaller

Requirements

Check

(env)$ python -V
Python 3.5.2

(env)$ pip freeze
PyInstaller==3.2

Build

(env)$ pyinstaller -F --hidden-import=win32timezone WindowsService.py

Run

(env) dist\WindowsService.exe install
Installing service TestService
Service installed

(env) dist\WindowsService.exe start
Starting service TestService

Clean

(env) dist\WindowsService.exe stop
(env) dist\WindowsService.exe remove
import servicemanager
import socket
import sys
import win32event
import win32service
import win32serviceutil
class TestService(win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
_svc_description_ = "My service description"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
rc = None
while rc != win32event.WAIT_OBJECT_0:
with open('C:\\TestService.log', 'a') as f:
f.write('test service running...\n')
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(TestService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(TestService)
@yon2004

This comment has been minimized.

Copy link

@yon2004 yon2004 commented Oct 16, 2017

Gold!

@bomlinh

This comment has been minimized.

Copy link

@bomlinh bomlinh commented Oct 17, 2017

Great! It saved my day.

@mewalig

This comment has been minimized.

Copy link

@mewalig mewalig commented Feb 1, 2018

any reason you know of this wouldn't also work for python 2.7?

@meatballs

This comment has been minimized.

Copy link

@meatballs meatballs commented Feb 15, 2018

Many thanks indeed. This inspired a piece of work at https://github.com/meatballs/AnvilUplinkWindowsService and I've given you an acknowledgement in the readme. Hope that's ok!

@gangzeng

This comment has been minimized.

Copy link

@gangzeng gangzeng commented Jun 7, 2018

great! I found many other examples not work. but this short one work! with python 3.6.2 and pyinstaller 3.3.1

@Yajan

This comment has been minimized.

Copy link

@Yajan Yajan commented Jun 15, 2018

Is it necessary to use ActivePython?.

@bharsaklemukesh975

This comment has been minimized.

Copy link

@bharsaklemukesh975 bharsaklemukesh975 commented Jul 4, 2018

I am using python3.7 on windows 10, the same code is not working.
"Python has stopped working" error is coming

@DAkbari

This comment has been minimized.

Copy link

@DAkbari DAkbari commented Jul 14, 2018

Thanks but, it doesn't work for me!
Error starting service: The service did not respond to the start or control request in a timely fashion.

@GhostofGoes

This comment has been minimized.

Copy link

@GhostofGoes GhostofGoes commented Jul 19, 2018

More complete example (and possibly the original source), for anyone interested: https://www.codeproject.com/Articles/1115336/Using-Python-to-Make-a-Windows-Service

@Yajan

This comment has been minimized.

Copy link

@Yajan Yajan commented Jul 19, 2018

How to use a input file for the service

@oraant

This comment has been minimized.

Copy link

@oraant oraant commented May 28, 2019

keep got errors like this for days, it's driving me crazy!!!!

(venv) E:\Software\PythonService>pyinstaller -F --hidden-import=win32timezone test.py

.........

Traceback (most recent call last):
  File "E:\Software\PythonService\venv\Scripts\pyinstaller-script.py", line 11, in <module>
    load_entry_point('PyInstaller==3.4', 'console_scripts', 'pyinstaller')()
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
    exec(text, spec_namespace)
  File "<string>", line 32, in <module>
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\building\api.py", line 424, in __init__
    strip_binaries=self.strip, upx_binaries=self.upx,
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\building\api.py", line 196, in __init__
    self.__postinit__()
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
    self.assemble()
  File "E:\Software\PythonService\venv\lib\site-packages\PyInstaller\building\api.py", line 273, in assemble
    pylib_name = os.path.basename(bindepend.get_python_library_path())
  File "D:\Program Files\Python3.7.2\lib\ntpath.py", line 214, in basename
    return split(p)[1]
  File "D:\Program Files\Python3.7.2\lib\ntpath.py", line 183, in split
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType
@prinsniels

This comment has been minimized.

Copy link

@prinsniels prinsniels commented Jun 4, 2019

Had the same problem, seems to be an issue with virtual env + py 3.7
Fixed it by replacing the bindepend.py file as described in:
https://stackoverflow.com/questions/54138898/an-error-for-generating-an-exe-file-using-pyinstaller-typeerror-expected-str

@XDavidT

This comment has been minimized.

Copy link

@XDavidT XDavidT commented Jul 17, 2019

I am using python3.7 on windows 10, the same code is not working.
"Python has stopped working" error is coming

Work's for me

@guillaumevincent

This comment has been minimized.

Copy link
Owner Author

@guillaumevincent guillaumevincent commented Jul 17, 2019

Sorry everybody, I don't have a windows machine to test and update this one
Feel free to put workarounds here or working gist

@Minobi

This comment has been minimized.

Copy link

@Minobi Minobi commented Feb 10, 2020

With Python 3.7.5 and PyInstaller 3.6 working on Windows 10 with venv.
Also may add _svc_description_ property to TestService class

@guillaumevincent

This comment has been minimized.

Copy link
Owner Author

@guillaumevincent guillaumevincent commented Feb 10, 2020

Can't test, but I updated the script
Thank you @Minobi

@kianoosh21

This comment has been minimized.

Copy link

@kianoosh21 kianoosh21 commented Mar 1, 2020

it needs an admin privilege to run so the first question is : how can i run cmd as admin by python3 and even when i'm in admin and type dist\WindowsService.exe start it returns me this error :


Starting service TestService
Error starting service: The service did not respond to the start or control request in a timely fashion.


any help would be appreciated.

@bennybar

This comment has been minimized.

Copy link

@bennybar bennybar commented Mar 30, 2020

amazing!

@wasimafser

This comment has been minimized.

Copy link

@wasimafser wasimafser commented Apr 6, 2020

it needs an admin privilege to run so the first question is : how can i run cmd as admin by python3 and even when i'm in admin and type dist\WindowsService.exe start it returns me this error :

Starting service TestService
Error starting service: The service did not respond to the start or control request in a timely fashion.

any help would be appreciated.

run Command Prompt as Admin

@LincolnPuzey

This comment has been minimized.

Copy link

@LincolnPuzey LincolnPuzey commented Apr 7, 2020

can anyone explain why the socket.setdefaulttimeout(60) line is required?

@XDavidT

This comment has been minimized.

Copy link

@XDavidT XDavidT commented Apr 7, 2020

can anyone explain why the socket.setdefaulttimeout(60) line is required?

Not sure about that. But when I used it in my app, I didn't include that line.
You can checkout my service (it's small part in large project)

@NatiBerko

This comment has been minimized.

Copy link

@NatiBerko NatiBerko commented Apr 16, 2020

Can anyone please help me i'm getting this error 1053 tried google and every thing i'm quit hopeless

@dishantrathi

This comment has been minimized.

Copy link

@dishantrathi dishantrathi commented Apr 18, 2020

Can anyone please help me i'm getting this error 1053 tried google and every thing i'm quit hopeless

Same is happening with me! @guillaumevincent

@guillaumevincent

This comment has been minimized.

Copy link
Owner Author

@guillaumevincent guillaumevincent commented Apr 18, 2020

can you give us more info?
like the python version, any logs, etc?
as I said before, I don't have a window computer any more, so it's difficult to test

@barathmeenachisundaram

This comment has been minimized.

Copy link

@barathmeenachisundaram barathmeenachisundaram commented Apr 27, 2020

Can anyone please help me i'm getting this error 1053 tried google and every thing i'm quit hopeless

Same is happening with me! @guillaumevincent

Same thing happened to me. What happened is, I checked whether it is working in as normal python file . so did python . So it told me servicemanager module missing. So installed it and tried again. Then i got this issue.
After lots of research, what i found is its because of wrong package being installed. So to resolve this, i created an new environment, and then did python install directly, instead of running it like a normal python file. It resolved my problem. Try this

@rickych1123

This comment has been minimized.

Copy link

@rickych1123 rickych1123 commented Jun 5, 2020

It works like a charm!

@zohaib055

This comment has been minimized.

Copy link

@zohaib055 zohaib055 commented Jun 15, 2020

how to start service auto ?

@scialuppa

This comment has been minimized.

Copy link

@scialuppa scialuppa commented Jul 12, 2020

It works, but you could tell me why in the event log Service Control Manager generates an alert with id 7039.

"A service process other than the one started by the Service Control Manager connected when the TestService service started. The Service Control Manager started the 6112 process and the 6480 process connected.

Note that if the service is configured to start inside a debugger, this behavior is expected. "

@guillaumevincent

This comment has been minimized.

Copy link
Owner Author

@guillaumevincent guillaumevincent commented Jul 13, 2020

To be honest I don't know

@97k

This comment has been minimized.

Copy link

@97k 97k commented Jul 18, 2020

Hi @guillaumevincent
Thank you for sharing this.

I have created a service and it is running fine. However, I am trying to build an installer.exe that will help end-user to install the service using the installation wizard of windows.

I am looking the web but couldn't get anything useful.

Can anyone help?

@wasimafser

This comment has been minimized.

Copy link

@wasimafser wasimafser commented Jul 18, 2020

I have created a service and it is running fine. However, I am trying to build an installer.exe that will help end-user to install the service using the installation wizard of windows.

https://youtu.be/_lmFArB6OI8 : watch from 03:00

@97k

This comment has been minimized.

Copy link

@97k 97k commented Jul 18, 2020

I have created a service and it is running fine. However, I am trying to build an installer.exe that will help end-user to install the service using the installation wizard of windows.

https://youtu.be/_lmFArB6OI8 : watch from 03:00

Hi @wasimafser

Thanks for the link, but I've already created the service exe and service is running just fine.
What I want is

  • to create a setup.exe installation wizard which the end user will install it just like any other software
  • After the user installs the service via setup.exe, the service will auto start at startup

I'm not able to make the installer for service that I've created

@wasimafser

This comment has been minimized.

Copy link

@wasimafser wasimafser commented Jul 18, 2020

@97k i'm extremely sorry, I got it wrong, BTW, i would create another executable which will be the installer, you could do it with python if you want, with it you could run commands required to install the service your way (example.. use subprocess and "sc install ..."). Bundle your service executable with this installer and distribute.
let me know if you find a better way .

@Minobi

This comment has been minimized.

Copy link

@Minobi Minobi commented Jul 18, 2020

What I want is

  • to create a setup.exe installation wizard which the end user will install it just like any other software
  • After the user installs the service via setup.exe, the service will auto start at startup

I'm not able to make the installer for service that I've created

@97k, maybe Inno setup or NSIS installers be suitable for this. I didn't do it myself, but I think they can be added to build process via PyInstaller build hooks.

@97k

This comment has been minimized.

Copy link

@97k 97k commented Jul 23, 2020

Hi @wasimafser, @Minobi!
I've solved the problem using Inno setup

I created a new exe file using pyinstaller that will take care of parameters -start, stop, remove
and used this new exe file with Inno setup.

Thanks for taking out time 😃

@Russell-Tran

This comment has been minimized.

Copy link

@Russell-Tran Russell-Tran commented Jan 27, 2021

great! I found many other examples not work. but this short one work! with python 3.6.2 and pyinstaller 3.3.1

Confirming this works with python 3.6.2 and pyinstaller 3.3.1. Didn't work with Python 3.9 for me

@Saleem344

This comment has been minimized.

Copy link

@Saleem344 Saleem344 commented Mar 30, 2021

Hi @wasimafser, @Minobi!
I've solved the problem using Inno setup

I created a new exe file using pyinstaller that will take care of parameters -start, stop, remove
and used this new exe file with Inno setup.

Thanks for taking out time 😃

Can send the process how you have used Inno setup.

@Saleem344

This comment has been minimized.

Copy link

@Saleem344 Saleem344 commented Mar 30, 2021

Hi Everyone I'm facing an issue while running a python script as a windows service can anyone help me??
Issue:

  1. I have created a python script for windows service, service is creating I can't able to run I'm getting the following error ( The pythonftp service terminated with the following service-specific error: Incorrect function.) in windows logs.
  2. I'm able to run the service from windows services, only if I'm creating service from the environment this is also working only on my laptop the same I have tried on another laptop I'm getting the same error.
  3. I'm sharing a screenshot for reference.
  4. code link: https://lnkd.in/gsuRPyh
  5. script name ftpservice.py
    #python3 #windows

error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment