以windows service方式运行Python程序的方法

yipeiwu_com5年前Python基础

本文实例讲述了以windows service方式运行Python程序的方法。分享给大家供大家参考。具体实现方法如下:

#!/usr/bin/env python 
# coding: utf-8 
# SmallestService.py 
# 
# A sample demonstrating the smallest possible service written in Python.
import win32serviceutil 
import win32service 
import win32event 
import time 
class SmallestPythonService(win32serviceutil.ServiceFramework): 
  _svc_name_ = "SmallestPythonService" 
  _svc_display_name_ = "The smallest possible Python Service" 
  def __init__(self, args): 
    win32serviceutil.ServiceFramework.__init__(self, args) 
    # Create an event which we will use to wait on. 
    # The "service stop" request will set this event. 
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 
  def SvcStop(self): 
    # Before we do anything, tell the SCM we are starting the stop process. 
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
    # And set my event. 
    win32event.SetEvent(self.hWaitStop) 
  def SvcDoRun(self): 
    #把你的程序代码放到这里就OK了 
    f=open('d:\\log.txt','w',0) 
    f.write(time.ctime(time.time())) 
    f.close() 
    win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) 
if __name__=='__main__': 
  win32serviceutil.HandleCommandLine(SmallestPythonService)  
  # 括号里的名字可以改成其他的,必须与class名字一致;

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python读取图片属性信息的实现方法

Python读取图片属性信息的实现方法

本文是利用Python脚本读取图片信息,有几个说明如下:      1、没有实现错误处理      2、没...

Python 修改列表中的元素方法

Python 修改列表中的元素方法

如下所示: #打印列表文件 def show_magicians(magics) : for magic in magics : print(magic) #修改列表文件...

Python中字符串的处理技巧分享

一、如何拆分含有多种分隔符的字符串? 实际案例 我们要把某个字符串依据分隔符号拆分不同的字符段,该字符串包含多种不同的分隔符,例如: s = 'asd;aad|dasd|dasd,...

用Python逐行分析文件方法

用于逐行分析文本的代码示例 fileIN = open(sys.argv[1], "r") line = fileIN.readline() while line: [some bi...

巧用python和libnmapd,提取Nmap扫描结果

每当我进行内网渗透面对大量主机和服务时,我总是习惯使用自动化的方式从 nmap 扫描结果中提取信息。这样有利于自动化检测不同类型的服务,例如对 web 服务进行路径爆破,测试 SSL/T...