我正在绘制一组程序的体系 struct ,这些程序共享存储在数据库中的各种相互关联的对象.我希望其中一个程序充当服务,为这些对象上的操作提供更高级别的接口,而其他程序则通过该服务访问这些对象.

我目前的目标是用Python和Django框架作为实现该服务的技术.我很确定我知道如何在Linux中对Python程序进行后台监控.但是,系统应支持Windows是可选的规范项.我对Windows编程几乎没有经验,对Windows服务也没有任何经验.

我不一定要实现这一部分,但我需要一个粗略的 idea ,以便决定是否按照这些思路进行设计.

Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?

推荐答案

是的,你可以.我使用ActivePython附带的pythoncom库或pywin32(Python for Windows extensions)安装的pythoncom库来实现这一点.

以下是简单服务的基本框架:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        pass

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

您的代码将进入main()方法,通常带有某种无限循环,该循环可能会被您在SvcStop方法中设置的标志所打断

Python相关问答推荐

如何从不同长度的HTML表格中抓取准确的字段?

避免循环的最佳方法

自定义新元未更新参数

具有2D功能的Python十六进制图

Python中的负前瞻性regex遇到麻烦

在函数内部使用eval(),将函数的输入作为字符串的一部分

通过优化空间在Python中的饼图中添加标签

DataFrame groupby函数从列返回数组而不是值

当使用keras.utils.Image_dataset_from_directory仅加载测试数据集时,结果不同

从收件箱中的列中删除html格式

从numpy数组和参数创建收件箱

如何从.cgi网站刮一张表到rame?

使用groupby Pandas的一些操作

Odoo 16使用NTFS使字段只读

如何在表中添加重复的列?

Pandas Loc Select 到NaN和值列表

字符串合并语法在哪里记录

使用Python和文件进行模糊输出

手动设置seborn/matplotlib散点图连续变量图例中显示的值

matplotlib图中的复杂箭头形状