如何让Windows识别我用Python编写的服务?
在我昨天发的另一个问题中,我得到了很好的建议,关于如何在Windows中将Python脚本作为服务运行。现在我想知道的是:Windows是怎么知道可以在本地工具(“管理工具”中的“服务”窗口)中管理的服务的?也就是说,Windows中相当于Linux下在/etc/init.d放启动/停止脚本的是什么呢?
4 个回答
7
这里有一段代码,可以把一个用Python写的脚本安装成服务哦 :)
http://code.activestate.com/recipes/551780/
这篇文章也可能对你有帮助:
http://essiene.blogspot.com/2005/04/python-windows-services.html
8
不要直接去修改注册表。使用 SC 命令行工具。具体来说,就是用 SC CREATE 命令。
DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ... The option has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService
3
在Windows系统中,很多“有意识”的东西都和“注册表”有关。
你可以看看这篇微软的知识库文章:http://support.microsoft.com/kb/103000
搜索一下“可以通过服务控制器启动的Win32程序,并且遵循服务控制协议。”这就是你需要关注的服务类型。
服务的注册信息(在KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\myservice这个位置)包含了关于服务的各种信息,比如它的可执行文件位置、出错时该怎么处理(是停止操作系统吗?)、在这个服务之前需要启动哪些服务,以及它是以哪个用户身份运行的。
至于服务控制协议,你的程序的main()函数应该调用Windows的API,设置一些回调函数来处理服务的启动、停止和暂停。至于在这些回调函数里做什么,那就完全由你决定了。