使用python?pywin32模塊創(chuàng)建windows服務(wù)實(shí)例探究
pywin32 模塊
在 Windows 上,Python 沒有內(nèi)置的守護(hù)進(jìn)程(daemon)模塊。但是你可以使用 pywin32 模塊來實(shí)現(xiàn)類似的功能。先安裝 pywin32 模塊,然后使用 pywin32 模塊調(diào)用 windows 服務(wù) API 創(chuàng)建一個(gè)后臺(tái)服務(wù)。
最終效果是在 services.msc 中會(huì)多出一個(gè)自定義的服務(wù):
安裝
在給出示例代碼前要先安裝 pywin32 模塊:
C:\> pip install pywin32
同時(shí)我們還會(huì)用到 psutil 獲取進(jìn)程 ID,需要安裝 psutil 模塊:
C:\> pip install psutil
先將進(jìn)程的PID寫入到指定的文件中
以下代碼實(shí)現(xiàn)了一個(gè)后臺(tái)進(jìn)程,它會(huì)先將進(jìn)程的PID寫入到指定的文件中,然后啟動(dòng)一個(gè)死循環(huán),每5秒打印一條消息代表進(jìn)程還存活著。
#!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) # 進(jìn)程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: # 在這里編寫你的守護(hù)進(jìn)程主要邏輯 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)
以管理員身份運(yùn)行 cmd,在命令行安裝當(dāng)前服務(wù):
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)注冊(cè)到系統(tǒng)服務(wù)中了。
此時(shí)可以在服務(wù)面板中對(duì)服務(wù)進(jìn)行啟停,也可以在命令行中對(duì)注冊(cè)的服務(wù)進(jìn)行啟停:
C:\> net stop MyPythonService My Python Service 服務(wù)正在停止.. My Python Service 服務(wù)已成功停止。 C:\> net start MyPythonService My Python Service 服務(wù)正在啟動(dòng) . My Python Service 服務(wù)已經(jīng)啟動(dòng)成功。
同時(shí),我們也可以在剛才的腳本執(zhí)行位置對(duì)注冊(cè)的服務(wù)進(jìn)行啟停:
d:\> python pyservices.py start Starting service MyPythonService d:\> python pyservices.py stop Stopping service MyPythonService d:\> python pyservices.py restart Restarting service MyPythonService
除了啟停服務(wù)之外,我們還能能 debug 方式運(yùn)行服務(wù)。當(dāng)以 debug 方式運(yùn)行時(shí),服務(wù)不會(huì)以后臺(tái)方式運(yùn)行,并且可以通過 ctrl+c 結(jié)束程序:
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...
當(dāng)代碼有更新時(shí)可以通過 update 命令更新服務(wù):
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āng)不再需要運(yùn)行此服務(wù)時(shí),可以注銷掉服務(wù):
d:\> python pyservices.py remove Removing service MyPythonService Service removed
以上就是使用python pywin32模塊創(chuàng)建windows服務(wù)實(shí)例探究的詳細(xì)內(nèi)容,更多關(guān)于python創(chuàng)建windows服務(wù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python getopt詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了 python getopt詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2016-12-12解決導(dǎo)入django_filters不成功問題No module named ''django_filter''
這篇文章主要介紹了解決導(dǎo)入django_filters不成功問題No module named 'django_filter',具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07python實(shí)現(xiàn)selenium網(wǎng)絡(luò)爬蟲的方法小結(jié)
這篇文章主要介紹了python實(shí)現(xiàn)selenium網(wǎng)絡(luò)爬蟲的方法小結(jié),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03Python利用shutil實(shí)現(xiàn)拷貝文件功能
shutil?是一個(gè)?Python?內(nèi)置模塊,該模塊對(duì)文件的復(fù)制、刪除和壓縮等操作都提供了非常方便的支持。本文將利用shutil實(shí)現(xiàn)拷貝文件功能,需要的可以參考一下2022-07-07Blender Python編程創(chuàng)建發(fā)光材質(zhì)示例詳解
這篇文章主要為大家介紹了Blender Python編程創(chuàng)建發(fā)光材質(zhì)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08matplotlib 曲線圖 和 折線圖 plt.plot()實(shí)例
這篇文章主要介紹了matplotlib 曲線圖 和 折線圖 plt.plot()實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04django學(xué)習(xí)之a(chǎn)jax post傳參的2種格式實(shí)例
AJAX除了異步的特點(diǎn)外,還有一個(gè)就是:瀏覽器頁面局部刷新,下面這篇文章主要給大家介紹了關(guān)于django學(xué)習(xí)之a(chǎn)jax post傳參的2種格式的相關(guān)資料,需要的朋友可以參考下2021-05-05