将Python脚本转换为Windows服务的问题

问题描述:

我已经有一个连续运行的python脚本。它与此非常相似:https://github.com/walchko/Black-Hat-Python/blob/master/BHP-Code/Chapter10/file_monitor.py将Python脚本转换为Windows服务的问题

与运行脚本时相似,它会打开一个CMD,它显示一些数据,当事情发生时 - 它不是用户可交互的,所以它不是强制性的,它显示(以防万一有人希望指出,Windows服务不能有接口)

我试图将其转换为服务。它开始几分之一秒,然后自动停止。当试图通过services.msc启动它(而不是python script.py start)时,它不会启动,Windows错误会显示如下内容:“本地计算机上的服务已启动,然后停止”,这听起来像是发生了什么我试着从争论开始。

我已经尝试修改脚本,使它能够作为服务运行 - 加入我发现这里的骨架:Is it possible to run a Python script as a service in Windows? If possible, how?

我也试过刚开上面的骨架脚本,只是试图使其运行另一个脚本与从这里的例子:What is the best way to call a Python script from another Python script?

有没有人有任何想法是什么最好的行动将是运行上面的脚本作为服务?

谢谢!

编辑

“......服务可以在计算机启动时,可以 暂停并重新启动,不显示任何用户界面自动启动。”Introduction to Windows Service Applications

的Windows服务要求的实施,提供一种特定的接口:

所以,你需要通过Python来访问Windows API:

你可以看到example code,从Python Programming On Win32,在其中第18章服务(ch18_services文件夹)中包含的样本(SmallestService。PY)演示用Python编写的最小可能的服务:

# SmallestService.py 
# 
# A sample demonstrating the smallest possible service written in Python. 

import win32serviceutil 
import win32service 
import win32event 

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): 
     # We do nothing other than wait to be stopped! 
     win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) 

if __name__=='__main__': 
    win32serviceutil.HandleCommandLine(SmallestPythonService) 

您可能需要下载相应的pywin32轮为您的特定Python环境在这里: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

而且install它(系统从admin cmd提示):

> cd \program files\python<ver>\scripts 
> pip install \path\to\pywin32‑221‑cp<ver>‑cp<ver>m‑win_<arch>.whl 

或安装它(每用户,从普通的命令提示符):

> cd \program files\python<ver>\scripts 
> pip install --user \path\to\pywin32‑221‑cp<ver>‑cp<ver>m‑win_<arch>.whl 

一定要更换的<ver><arch>适当的出现次数。

+0

感谢您的信息!如果我想让这个服务运行我的其他脚本,我的代码应该在哪里以及如何运行?我应该在win32serviceutil.HandleCommandLine(SmallestPythonService)下放置一些类似subprocess.call(“script.py”)的东西吗? –

+0

尝试从SvcDoRun()函数内开始脚本。 – veganaiZe

+0

我接受了你的答案,因为它工作。该服务正在安装,脚本开始在我使用“python script.py install”命令的同一个CMD中运行。但是它并没有开始,只有当我离开CMD窗口时它才会工作。我得到这个:“实例的SvcRun()方法失败