以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 ,PIL,selenium pycharm 三....

解决python 3 urllib 没有 urlencode 属性的问题

今天在pycharm(我用的python3)练习的时候,发现报了个AttributeError: module 'urllib' has no attribute 'urlencode'...

通过Python来使用七牛云存储的方法详解

通过Python来使用七牛云存储的方法详解

本教程旨在介绍如何使用七牛的Python SDK来快速地进行文件上传,下载,处理,管理等工作。 安装 首先,要使用Python的SDK必须要先安装。七牛的Python SDK是开源的,托...

python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法

Python的字符集处理实在蛋疼,目前使用UTF-8居多,然后默认使用的字符集是ascii,所以我们需要改成utf-8 查看目前系统字符集 复制代码 代码如下: import sys p...

Django 实现图片上传和显示过程详解

第1章 新建工程和创建app 新建工程和创建app就不用贴出来了,我这里是测试图片上传的功能能否实现,所以项目都是新的,正常在以有的app下就可以 第2章 模型层: 2.1创建数据库...