我正在描绘一组程序的架构,这些程序共享存储在数据库中的各种相互关联的对象.我希望其中一个程序充当服务,为这些对象的操作提供更高级别的接口,以及通过该服务访问对象的其他程序.
我目前的目标是将Python和Django框架作为实现该服务的技术.我很确定我想知道如何在Linux中守护Python程序.但是,它是系统应支持Windows的可选规范项.我对Windows编程没什么经验,也没有Windows服务的经验.
是否可以将Python程序作为Windows服务运行(即在没有用户登录的情况下自动运行)?我不一定要实现这一部分,但我需要大致了解如何做以决定是否按照这些方式进行设计.
编辑:感谢目前为止的所有答案,它们非常全面.我想知道一件事:Windows如何了解我的服务?我可以使用本机Windows实用程序进行管理吗? 在/etc/init.d中放置一个启动/停止脚本相当于什么?
我目前正在尝试使用pywin32创建win32服务.我的主要参考点是本教程:
http://code.activestate.com/recipes/551780/
我不明白的是初始化过程,因为守护进程永远不会被Daemon()直接初始化,而是我的理解它由以下内容初始化:
mydaemon = Daemon
__svc_regClass__(mydaemon, "foo", "foo display", "foo description")
__svc_install__(mydaemon)
Run Code Online (Sandbox Code Playgroud)
其中svc_install通过调用守护进程来处理初始化.init()并将一些参数传递给它.
但是,如何在不使用服务的情况下初始化守护进程对象?在我启动服务之前,我想做一些事情.有没有人有任何想法?
class Daemon(win32serviceutil.ServiceFramework):
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcDoRun(self):
self.run()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def start(self):
pass
def stop(self):
self.SvcStop()
def run(self):
pass
def __svc_install__(cls):
win32api.SetConsoleCtrlHandler(lambda x: True, True)
try:
win32serviceutil.InstallService(
cls._svc_reg_class_,
cls._svc_name_,
cls._svc_display_name_,
startType = win32service.SERVICE_AUTO_START
)
print "Installed"
except Exception, err:
print str(err)
def __svc_regClass__(cls, name, display_name, description):
#Bind the values …Run Code Online (Sandbox Code Playgroud) 由于可以在Windows中运行Python脚本作为服务,我能够将我的烧瓶应用程序作为服务运行吗?如果可能,怎么样?,但是当它停止它我不能.我必须在任务管理器中终止该过程.
这是我的run.py,我通过run.py install变成了一个服务:
from app import app
from multiprocessing import Process
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "CCApp"
_svc_display_name_ = "CC App"
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)
server.terminate()
server.join()
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
server = Process(app.run(host = '192.168.1.6'))
server.start()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
Run Code Online (Sandbox Code Playgroud)
我从这篇文章中得到了这个过程的内容:http://librelist.com/browser/flask/2011/1/10/start-stop-flask/#a235e60dcaebaa1e134271e029f801fe,但遗憾的是它也不起作用.
事件查看器中的日志文件表示未定义全局变量"server".但是,我已经使服务器成为一个全局变量,它仍然给我同样的错误.