python可以在windows下运行吗_在Windows中作为服务运行Python web服务器

我有一个用Python编写的小型web服务器应用程序,它从数据库系统获取一些数据,并将其作为XML返回给用户。这部分工作得很好-我可以从命令行运行Python web服务器应用程序,我可以让客户机连接到它并获取数据。目前,要运行web服务器,我必须以管理员用户的身份登录到服务器,并手动启动web服务器。我想让web服务器作为服务在系统启动时自动启动并在后台运行。

使用来自ActiveState网站和StackOverflow的代码,我对如何创建服务有了很好的了解,我想我已经对它进行了排序——我可以将我的web服务器作为Windows服务安装和启动。但是,我想不出如何再次停止服务。我的web服务器是从BaseHTTPServer创建的:server = BaseHTTPServer.HTTPServer(('', 8081), SIMSAPIServerHandler)

server.serve_forever()

serve_forever()调用自然会使web服务器处于无限循环中,等待HTTP连接(或ctrl-break-keypress,对服务无效)。我从上面的示例代码中了解到,main()函数应该位于无限循环中,只有在遇到“stop”条件时才会中断。我的主叫永远服务于你。我有一个SvcStop函数:def SvcStop(self):

self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

exit(0)

当我从命令行执行“python myservice stop”时(我可以在其中放置一个调试行,生成文件的输出),它似乎会被调用,但实际上并没有退出整个服务-随后对“python myservice start”的调用会给我一个错误:Error starting service: An instance of

the service is already running.

随后的叫停让我:Error stopping service: The service

cannot accept control messages at this

time. (1061)

我想我需要一个永久服务的替代品(服务直到收到服务为止,或者别的什么),或者我需要一些修改SvcStop的方法,这样它就停止了整个服务。

下面是一个完整的列表(我已经修剪了includes/comments以节省空间):class SIMSAPIServerHandler(BaseHTTPServer.BaseHTTPRequestHandler):

def do_GET(self):

try:

reportTuple = self.path.partition("/")

if len(reportTuple) < 3:

return

if reportTuple[2] == "":

return

os.system("C:\\Programs\\SIMSAPI\\runCommandReporter.bat " + reportTuple[2])

f = open("C:\\Programs\\SIMSAPI\\out.xml", "rb")

self.send_response(200)

self.send_header('Content-type', "application/xml")

self.end_headers()

self.wfile.write(f.read())

f.close()

# The output from CommandReporter is simply dumped to out.xml, which we read, write to the user, then remove.

os.unlink("C:\\Programs\\SIMSAPI\\out.xml")

return

except IOError:

self.send_error(404,'File Not Found: %s' % self.path)

class SIMSAPI(win32serviceutil.ServiceFramework):

_svc_name_ = "SIMSAPI"

_svc_display_name_ = "A simple web server"

_svc_description_ = "Serves XML data produced by SIMS CommandReporter"

def __init__(self, args):

win32serviceutil.ServiceFramework.__init__(self, args)

self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

def SvcStop(self):

self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

exit(0)

def SvcDoRun(self):

import servicemanager

servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))

self.timeout = 3000

while 1:

server = BaseHTTPServer.HTTPServer(('', 8081), SIMSAPIServerHandler)

server.serve_forever()

def ctrlHandler(ctrlType):

return True

if __name__ == '__main__':

win32api.SetConsoleCtrlHandler(ctrlHandler, True)

win32serviceutil.HandleCommandLine(SIMSAPI)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值