使用python?pywin32模塊創(chuàng)建windows服務實例探究
pywin32 模塊
在 Windows 上,Python 沒有內(nèi)置的守護進程(daemon)模塊。但是你可以使用 pywin32 模塊來實現(xiàn)類似的功能。先安裝 pywin32 模塊,然后使用 pywin32 模塊調(diào)用 windows 服務 API 創(chuàng)建一個后臺服務。
最終效果是在 services.msc 中會多出一個自定義的服務:
安裝
在給出示例代碼前要先安裝 pywin32 模塊:
C:\> pip install pywin32
同時我們還會用到 psutil 獲取進程 ID,需要安裝 psutil 模塊:
C:\> pip install psutil
先將進程的PID寫入到指定的文件中
以下代碼實現(xiàn)了一個后臺進程,它會先將進程的PID寫入到指定的文件中,然后啟動一個死循環(huán),每5秒打印一條消息代表進程還存活著。
#!python3 # Filename: pyservices.py import win32serviceutil import win32service import win32event import servicemanager import socket import sys import time import psutil def write_process_id_to_file(file_path): pid = str(psutil.Process().pid) with open(file_path, 'w') as file: file.write(pid) # 進程ID process_id_file_path = r"d:\MyPythonService.pid" class MyService(win32serviceutil.ServiceFramework): _svc_name_ = "MyPythonService" _svc_display_name_ = "My Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) self.is_alive = True def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.is_alive = False def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() def main(self): write_process_id_to_file(process_id_file_path) while self.is_alive: # 在這里編寫你的守護進程主要邏輯 print("Daemon is running...") time.sleep(5) if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(MyService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(MyService)
以管理員身份運行 cmd,在命令行安裝當前服務:
d:\> python pyservices.py install Installing service MyPythonService copying host exe 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32\pythonservice.exe' -> 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\pythonservice.exe' copying helper dll 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pywin32_system32\pywintypes311.dll' -> 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\pywintypes311.dll' Service installed
services.msc查看MyPythonService
安裝完后即可在 services.msc 中查看到 MyPythonService 已經(jīng)注冊到系統(tǒng)服務中了。
此時可以在服務面板中對服務進行啟停,也可以在命令行中對注冊的服務進行啟停:
C:\> net stop MyPythonService My Python Service 服務正在停止.. My Python Service 服務已成功停止。 C:\> net start MyPythonService My Python Service 服務正在啟動 . My Python Service 服務已經(jīng)啟動成功。
同時,我們也可以在剛才的腳本執(zhí)行位置對注冊的服務進行啟停:
d:\> python pyservices.py start Starting service MyPythonService d:\> python pyservices.py stop Stopping service MyPythonService d:\> python pyservices.py restart Restarting service MyPythonService
除了啟停服務之外,我們還能能 debug 方式運行服務。當以 debug 方式運行時,服務不會以后臺方式運行,并且可以通過 ctrl+c 結束程序:
d:\> python pyservices.py debug Debugging service MyPythonService - press Ctrl+C to stop. Info 0x40001002 - The MyPythonService service has started. Daemon is running... Daemon is running... Daemon is running...
當代碼有更新時可以通過 update 命令更新服務:
d:\> python pyservices.py update Changing service configuration copying host exe 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32\pythonservice.exe' -> 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\pythonservice.exe' Service updated
當不再需要運行此服務時,可以注銷掉服務:
d:\> python pyservices.py remove Removing service MyPythonService Service removed
以上就是使用python pywin32模塊創(chuàng)建windows服務實例探究的詳細內(nèi)容,更多關于python創(chuàng)建windows服務的資料請關注腳本之家其它相關文章!
相關文章
解決導入django_filters不成功問題No module named ''django_filter''
這篇文章主要介紹了解決導入django_filters不成功問題No module named 'django_filter',具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07python實現(xiàn)selenium網(wǎng)絡爬蟲的方法小結
這篇文章主要介紹了python實現(xiàn)selenium網(wǎng)絡爬蟲的方法小結,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Blender Python編程創(chuàng)建發(fā)光材質示例詳解
這篇文章主要為大家介紹了Blender Python編程創(chuàng)建發(fā)光材質示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08matplotlib 曲線圖 和 折線圖 plt.plot()實例
這篇文章主要介紹了matplotlib 曲線圖 和 折線圖 plt.plot()實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04django學習之a(chǎn)jax post傳參的2種格式實例
AJAX除了異步的特點外,還有一個就是:瀏覽器頁面局部刷新,下面這篇文章主要給大家介紹了關于django學習之a(chǎn)jax post傳參的2種格式的相關資料,需要的朋友可以參考下2021-05-05