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

相关文章

PYTHON 中使用 GLOBAL引发的一系列问题

哪里出问题了   python 中,使用 global 会将全局变量设为本函数可用。同时,在函数内部访问变量会先本地再全局。   在嵌套函数中,使用 global 会产生不合常理的行为。...

解决python2.7 查询mysql时出现中文乱码

问题: python2.7 查询或者插入中文数据在mysql中的时候出现中文乱码 --- 可能情况: 1.mysql数据库各项没有设置编码,默认为'latin' 2.使用MySQL...

tensorflow实现简单逻辑回归

逻辑回归是机器学习中很简答的一个栗子,这篇文章就是要介绍如何使用tensorflow实现一个简单的逻辑回归算法。 逻辑回归可以看作只有一层网络的前向神经网络,并且参数连接的权重只是一个值...

Python入门之三角函数全解【收藏】

Python中的三角函数位于math模块内。 引入模块: import math 输出pi: import math print(math.pi) 得:3.14159265358979...

纯用NumPy实现神经网络的示例代码

纯用NumPy实现神经网络的示例代码

摘要: 纯NumPy代码从头实现简单的神经网络。 Keras、TensorFlow以及PyTorch都是高级别的深度学习框架,可用于快速构建复杂模型。前不久,我曾写过一篇文章...