将一个python程序改写成一个windows服务

 时间:2024-10-13 09:36:12

1、import win补朱锚卦32serviceutilimport win32serviceimport win泌驾台佐32eventimport osimport socketclass PythonService(win32serviceutil.ServiceFramework): #服务名 _svc_name_ = "weater" #服务显示名称 _svc_display_name_ = "weater" #服务描述 _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 = Falseif __name__=='__main__': win32serviceutil.HandleCommandLine(PythonService)

2、只需要将代码中的 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端口是否是开启状态,如果关闭了就执行启动命令,用于实现程序的后台稳定运行。

3、Windows下将服务安装到系统方法:安装服务python PythonService.py install让服务自动启动python PythonService.py --startup auto install启动服务python PythonService.py start重启服务python PythonService.py restart停止服务python PythonService.py stop删除/卸载服务python PythonService.py remove使用pyinstaller打包为exe可放到任意机器上安装服务:D:\python\Scripts>pyinstaller -F --hidden-import=win32timezone D:\test\test.py

  • vmware虚拟机克隆功能
  • WPS表格如何取消科学计数法?
  • 怎样保养和维护鱼钩
  • EZDML表结构设计器使用详细教程
  • 易语言窗口界面如何添加目录框
  • 热门搜索
    国内冬季旅游景点排行 热浪岛旅游攻略 野山坡旅游景点路线 陕西汉中旅游景点大全 travelzoo旅游族 特价旅游团 河南冬季旅游景点 去日本旅游攻略 春节短途旅游推荐 江西的旅游景点