如何在Windows中将Python脚本作为服务运行?
我正在草绘一组程序的体系结构,这些程序共享存储在数据库中的各种相互关联的对象。我希望其中一个程序充当服务,为这些对象的操作提供更高级别的接口,而其他程序则通过该服务访问对象。
我目前的目标是将Python和Django框架作为实现该服务的技术。我很确定我知道如何守护Linux中的Python程序。但是,这是系统应支持Windows的可选规格。我几乎没有Windows编程经验,也没有Windows服务经验。
是否可以将Python程序作为Windows服务运行(即无需用户登录即可自动运行)?我不必一定要实现这一部分,但是我需要一个大概的想法,即如何决定是否按照这些原则进行设计。
编辑:感谢到目前为止的所有答案,它们很全面。我想知道一件事:Windows如何了解我的服务?我可以使用本地Windows实用程序对其进行管理吗?将启动/停止脚本放入/etc/init.d相当于什么?
解决方案
回答
是的你可以。我使用ActivePython随附的pythoncom库或者可以与pywin32(适用于Windows的Python扩展)一起安装的方式来执行此操作。
这是简单服务的基本框架:
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`方法中设置的标志而中断。
回答
实际上,有两种方法可以将任何Windows可执行文件作为服务安装。
方法1:从rktools.exe使用instsrv和srvany
对于Windows Home Server或者Windows Server 2003(也可与WinXP一起使用),Windows Server 2003 Resource Kit Tools附带了可以串联使用的实用程序,称为instsrv.exe和srvany.exe。有关如何使用这些实用程序的详细信息,请参见此Microsoft KB文章KB137890。
对于Windows Home Server,这些实用程序都有一个很好的用户友好包装,其名称恰当地为" Any Service Installer"。
方法2:使用Windows NT的ServiceInstaller
使用适用于Windows NT的ServiceInstaller(可在此处下载)的另一种方法是使用python指令。与名称相反,它也适用于Windows 2000和Windows XP。以下是有关如何将python脚本作为服务安装的一些说明。
Installing a Python script Run ServiceInstaller to create a new service. (In this example, it is assumed that python is installed at c:\python25) Service Name : PythonTest Display Name : PythonTest Startup : Manual (or whatever you like) Dependencies : (Leave blank or fill to fit your needs) Executable : c:\python25\python.exe Arguments : c:\path_to_your_python_script\test.py Working Directory : c:\path_to_your_python_script After installing, open the Control Panel's Services applet, select and start the PythonTest service.
在最初回答之后,我注意到SO上已经发布了密切相关的问答。也可以看看:
我可以将Python脚本作为服务运行(在Windows中)吗?如何?
如何使Windows知道我用Python编写的服务?