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

2024-10-03 06:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经有了一个连续运行的python脚本。它非常类似于这个:https://github.com/walchko/Black-Hat-Python/blob/master/BHP-Code/Chapter10/file_monitor.py

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

我试着把它转换成服务。它会在几秒钟内启动,然后自动停止。当试图通过服务.msc(而不是python脚本.py启动)它根本不启动,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?

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

谢谢!在


Tags: topyhttpsgithub脚本com框架windows
1条回答
网友
1楼 · 发布于 2024-10-03 06:24:25

编辑

"...services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface." ~Introduction to Windows Service Applications

Windows服务要求实现使特定接口可用:

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

您可以从Python Programming On Win32中看到example code,其中第18章服务(ch18_Services文件夹)包含一个示例(最小服务.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控制盘: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32

install它(系统范围内,从admin cmd提示符):

^{pr2}$

或安装(每个用户,从常规cmd提示符):

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

确保适当地替换<ver><arch>的出现。

相关问题 更多 >