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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Flask和Django框架中自定义模型类的表名、父类相关问题分析

本文实例分析了Flask和Django框架中自定义模型类的表名、父类相关问题。分享给大家供大家参考,具体如下: 一. Flask和Django中定义表名(执行迁移后生成)的方式和flas...

详解Python中DOM方法的动态性

详解Python中DOM方法的动态性

文档对象模型 xml.dom 模块对于 Python 程序员来说,可能是使用 XML 文档时功能最强大的工具。不幸的是,XML-SIG 提供的文档目前来说还比较少。W3C 语言无关的 D...

Django中url的反向查询的方法

Django中url的反向查询的方法

本文介绍了Django中url的反向查询的方法,分享给大家,具体如下: 明确几个概念: 1、application namespace : 正在部署的app的名称,一个app的多个...

Python sys.argv用法实例

sys.argv变量是一个字符串的列表。特别地,sys.argv包含了命令行参数 的列表,即使用命令行传递给你的程序的参数。 这里,当我们执行python using_sys.py we...

使用Python实现从各个子文件夹中复制指定文件的方法

之前用来整理图片的小程序,拿来备忘,算是使用Python复制文件的一个例子。 # -*- coding: utf-8 -*- #程序用来拷贝文件并输出图片采集日期等其他信息到Exce...