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

相关文章

Pycharm 2020年最新激活码(亲测有效)

PyCharm 具备一般 IDE 的功能,比如,调试、语法高亮、项目管理、代码跳转、智能提示、自动完成、单元测试、版本控制…另外,PyCharm 还提供了一些很好的功能用于 Django...

python 简易计算器程序,代码就几行

代码: 复制代码 代码如下: import os while True: dynamic = input('输入计算表达式:') if dynamic != 'cls': try: re...

python统计一个文本中重复行数的方法

本文实例讲述了python统计一个文本中重复行数的方法。分享给大家供大家参考。具体实现方法如下: 比如有下面一个文件 2 3 1 2 我们期望得到 2,2 3,1 1,1 解决问题的思路...

Python中模块pymysql查询结果后如何获取字段列表

前言 大家在使用pymysql的时候,通过fetchall()或fetchone()可以获得查询结果,但这个返回数据是不包含字段信息的(不如php方便)。查阅pymysql源代码后,其实...

python动态加载包的方法小结

本文实例总结了python动态加载包的方法。分享给大家供大家参考,具体如下: 动态加载模块有三种方法 1. 使用系统函数__import_() stringmodule = __im...