# -*- coding: utf-8 -*-
import sys import win32api
import win32con
import win32event
import win32service
import win32serviceutil
import servicemanager
import logging
import os
from http.server import HTTPServer, CGIHTTPRequestHandler class HTTPFilerServer(win32serviceutil.ServiceFramework):
_svc_name_ = "HTTPFileServer"
_svc_display_name_ = "HTTP File Server"
_svc_description_ = "HTTP File Server"
_svc_data_dir = 'D:\\ScreenRecorder' def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
self.logger = self._getLogger() def _getLogger(self): logger = logging.getLogger('[HTTPFileServer]')
dirpath = os.path.abspath(self._svc_data_dir)
handler = logging.FileHandler(os.path.join(dirpath, self._svc_name_ + ".log")) formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter) logger.addHandler(handler)
logger.setLevel(logging.INFO) return logger def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.logger.info('HTTP File Server is Starting ...')
self.start()
self.logger.info('HTTP File Server Started')
import time
time.sleep(3)
os.chdir(self._svc_data_dir)
httpd = HTTPServer(('', 8080), CGIHTTPRequestHandler)
httpd.serve_forever() win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
self.logger.info('HTTP File Server Shutdown')
except BaseException as e:
self.logger.warn('Exception : %s' % e)
self.SvcStop() def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.logger.info('HTTP File Server is Stopping ...')
self.stop()
self.logger.info('HTTP File Server Service Stopped')
win32event.SetEvent(self.stop_event)
self.ReportServiceStatus(win32service.SERVICE_STOPPED) def start(self):
if not os.path.exists(self._svc_data_dir):
os.mkdir(self._svc_data_dir)
win32api.SetFileAttributes(self._svc_data_dir, win32con.FILE_ATTRIBUTE_HIDDEN)
else:
pass def stop(self):
pass def log(self, msg):
servicemanager.LogInfoMsg(str(msg)) if __name__ == "__main__":
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(HTTPFilerServer)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(HTTPFilerServer)

Python 实现windows后台服务的更多相关文章

  1. 【JavaService】部署Java jar为Windows后台服务

    将Java jar文件部署为Windows后台服务有多种方法:Service Installer.Java service Wrapper.JavaService.exe等等.这里介绍下使用JavaS ...

  2. 使用instsrv.exe和srvany.exe将应用程序安装成windows后台服务

    好的参考链接: http://www.jb51.net/softjc/374631.html 利用这两个工具,将 exe程序或者 bat文件,做成Windows后台服务.

  3. 番外篇:使用nssm工具将ES、Kibana、Logstash或者其他.bat文件部署为Windows后台服务的方法

    使用NSSM工具安装bat文件为Windows服务 nssm是一个可以把bat批处理文件部署为Windows服务的小工具.例如很多.net项目可能还是在Windows服务器上面跑的,但是很多组件只提供 ...

  4. python杀死Windows后台程序

    检测 "sogou-gui.exe" 的进程可用tasklist命令 tasklist /FI "IMAGENAME eq sogou-gui.exe" FI: ...

  5. linux/windows下启用和停止VMware后台服务的脚本

    linux/windows下启用和停止VMware后台服务的脚本 linux/windows下启用和停止VMware后台服务的脚本 linux平台 windows平台 本文由乌合之众 lym瞎编,欢迎 ...

  6. Python做windows服务

    Python做windows服务(多进程服务),并结束多进程 Python中_,__,__xx__的区别 在注册MyWinService服务时,再使用 "sc delete 服务器名称&qu ...

  7. 在windows中:双击运行Python程序、后台运行Python程序

    在windows中:双击运行Python程序.后台运行Python程序 安装Python解释器的windows环境,如果双击运行*.py的文件,会闪退.怎样避免闪退呢? 我们用python的日志输出程 ...

  8. redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(多机)

    redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(多机) 一.概述 此教程介绍如何在windows系统中多个服务器之间,布置redis哨兵模式(主从复制),同时要以后台服务的模式运行 ...

  9. redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(单机)

    redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(单机) 一.概述 此教程介绍如何在windows系统中单机布置redis哨兵模式(主从复制),同时要以后台服务的模式运行.布置以脚本 ...

随机推荐

  1. Docker Mysql主从同步配置搭建Demo

    进行Docker操作前,先建立目录,我的路径是d:/docker/mysql,目录结构如下: --mysql --master --data --conf --my.cnf --slaver --da ...

  2. 【Detection】R-FCN: Object Detection via Region-based Fully Convolutional Networks论文分析

    目录 0. Paper link 1. Overview 2. position-sensitive score maps 2.1 Background 2.2 position-sensitive ...

  3. 配置spring boot 内置tomcat的accessLog日志

    #配置内置tomcat的访问日志server.tomcat.accesslog.buffered=trueserver.tomcat.accesslog.directory=/home/hygw/lo ...

  4. linux一键修改mysql密码脚本

    乱七八糟的shell脚本大集合 #!/bin/bash mysql_root_pwd=$( ; echo) mysql_cnf_path=$ export mysql_passwd=$mysql_ro ...

  5. NPM Scripts -- onchange parallelshell

    Watch for changes to the styles.scss file and automatically compile it to the css file. Run multiple ...

  6. tp5---树形菜单

    composer require bluem/tree

  7. 【Python】学习笔记之函数

    Python函数 在Python中,一切皆为对象,函数也可以赋给一个变量,就是指向一个函数对象的引用,相当于给这个函数起了一个“别名”: >>> a = max >>&g ...

  8. head first python选读(5)

    python web 开发 犯了低级错误,这本书看了一半了才知道书名应为<head first python>,不是hand first.. 现在开始一个web应用. 总算是熟悉的内容了. ...

  9. 使用sha512算法加密linux密码

    查看当前主机的加密算法: [root@realserver ~]# authconfig --test |grep hashing password hashing algorithm is sha5 ...

  10. C++(三十二) — 常对象、常成员变量、常成员函数

    常量:对于既需要共享.又需要防止改变的数据.在程序运行期间不可改变. const 修饰的是对象中的 this 指针.所以不能被修改. 1.常对象 数据成员值在对象的整个生存期内不能改变.在定义时必须初 ...