工具/原料
方法/步骤
import sys import servicemanager import win32serviceutil import win32service import win32event import os import socket class xm58pxeService(win32serviceutil.ServiceFramework): # 服务名 _svc_name_ = "xm58pxe" # 服务显示名称 _svc_display_name_ = "xm58pxe" # 服务描述 _svc_description_ = "爱尚教程网专用服务" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.isAlive = True def SvcDoRun(self): import time while self.isAlive: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1', 80)) if result != 0: os.popen('python D:\\test\\web_Django\\we\\manage.py runserver 0.0.0.0:80') time.sleep(8) sock.close() time.sleep(20) def SvcStop(self): # 先告诉SCM停止这个过程 self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # 设置事件 win32event.SetEvent(self.hWaitStop) self.isAlive = False if __name__ == '__main__': if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(xm58pxeService) servicemanager.Initialize('xm58pxeService', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except Exception as e: print(e) else: win32serviceutil.HandleCommandLine(xm58pxeService)
2.只需要将代码中的文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1', 80)) if result != 0: os.popen('python D:\\test\\web_Django\\we\\manage.py runserver 0.0.0.0:80') time.sleep(8) sock.close()
替换成自己需要执行的事件即可,我这个示例的意思是循环监控80端口是否是开启状态,如果关闭了就执行启动命令,用于实现程序的后台稳定运行。文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
安装服务文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
python PythonService.py install
让服务自动启动文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
python PythonService.py --startup auto install
启动服务文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
python PythonService.py start
重启服务文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
python PythonService.py restart
停止服务文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
python PythonService.py stop
删除/卸载服务文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
python PythonService.py remove
使用pyinstaller打包为exe可放到任意机器上安装服务:文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
D:\python\Scripts>文章源自爱尚资源教程网-https://www.23jcw.net/5779.html
pyinstaller -F --hidden-import=win32timezone D:\test\test.py
相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!