将Python脚本转换为Windows服务时出现问题

将Python脚本转换为Windows服务时出现问题,python,windows-services,Python,Windows Services,我已经有了一个连续运行的python脚本。与此非常相似: 与中类似,当它作为脚本运行时,它会打开一个CMD,在发生事情时显示一些数据-它不是用户可交互的,因此它不是强制显示的(以防有人希望指出windows服务不能有接口) 我试着把它转换成服务。它启动一小部分秒,然后自动停止。当尝试通过services.msc(而不是python script.py start)启动它时,它根本不会启动,Windows错误会显示类似于“本地计算机上的服务启动然后停止”的内容,这听起来与我尝试使用参数启动它时发生

我已经有了一个连续运行的python脚本。与此非常相似:

与中类似,当它作为脚本运行时,它会打开一个CMD,在发生事情时显示一些数据-它不是用户可交互的,因此它不是强制显示的(以防有人希望指出windows服务不能有接口)

我试着把它转换成服务。它启动一小部分秒,然后自动停止。当尝试通过services.msc(而不是python script.py start)启动它时,它根本不会启动,Windows错误会显示类似于“本地计算机上的服务启动然后停止”的内容,这听起来与我尝试使用参数启动它时发生的情况差不多

我已尝试修改脚本以允许它作为服务运行-添加我在此处找到的框架:

我还尝试获取上面的骨架脚本,并尝试使用下面的示例使其运行其他脚本:

有人知道将上面的脚本作为服务运行的最佳做法是什么吗

谢谢

已编辑

“…当计算机启动时,服务可以自动启动,可以 已暂停并重新启动,不显示任何用户界面。“~

Windows服务需要实现使特定的界面可用:

因此您需要通过Python访问Windows API:

您可以从中看到,其中第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)

您可能需要在此处下载适合您特定python环境的pywin32控制盘:

和it(系统范围,从admin cmd提示符):

>cd\program files\python\scripts
>pip安装\path\to\pywin32‑221‑cp‑cpm‑win.\whl
或安装它(每个用户,从常规cmd提示符):

>cd\program files\python\scripts
>pip安装--user\path\to\pywin32-221-cp-cpm-win\u1.whl

请确保适当地替换出现的

谢谢您提供的信息!如果我想让服务运行我的另一个脚本,那么我的代码应该在哪里运行,应该如何运行?我是否应该在win32serviceutil.HandleCommandLine(SmallestPythonService)下放一些类似subprocess.call(“script.py”)的东西?尝试从SvcDoRun()函数内部启动脚本。我接受了您的答案,因为它可以正常工作。服务正在安装,脚本开始在我在上使用“pythonscript.pyinstall”命令的同一CMD中运行。但它并没有启动,只有在我打开CMD窗口的情况下,它才能工作。我明白了:“实例的SvcRun()方法失败了。您还需要适当地调整
\uuu init\uuu
SvcStop()
中的代码;请记住,这是最小的,因此您可能需要在现有函数中添加其他函数或更多代码。
> 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