免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4885 | 回复: 3

求教:如何才能启动PYTHON 写的WINDOWS服务? [复制链接]

论坛徽章:
0
发表于 2007-05-14 22:15 |显示全部楼层
各位高手:
我用PYTHON 写了个WINDOWS服务程序. 能够在DEBUG状态下成功运行.
但是用PY2EXE编译后,INSTALL成服务,则不能启动.报 :
The Test Remote Server service failed to start due to the following error:
The service did not respond to the start or control request in a timely fashion.
Timeout (30000 milliseconds) waiting for the Test Remote Server service to connect.

    源程序如下 , 请各位帮忙指点迷津.感激不尽 !!!!!!!
import socket

import os
import random
import threading
import time
import select
import string


import win32serviceutil
import win32service
import win32event



class CreateServerSocket:
    def __init__(self):
        
        self.local_socket = socket.socket( socket.AF_INET ,socket.SOCK_STREAM)
        
        try :
            local_ip   = ConnectToMultiMXV.GetLocalIPAddress()
            local_port = 12000
            address    = (local_ip ,local_port)
            self.local_socket.bind(address)
            self.local_socket.listen(5)
            print "Server is listening on Port %s in %s ..." % (local_port ,local_ip)
        except socket.error :
            print "Can not connect to the %s." % (local_ip)
            
   
   
    def __del__(self):
        self.local_socket.close()
        del(self.local_socket)
   
   
class OperateKCAsThread(threading.Thread):
    def __init__(self , connection ,logfile , callback):
        threading.Thread.__init__(self)
        self.connection = connection
        self.filename   = str(random.randint(255 ,300)) + ".tmp"
        self.logfile    = logfile
        self.CallBack   = callback
      
    def writelog(self ,message):   
        self.logfile.write(time.asctime() + "--" + message + '\n')
        self.logfile.flush()


    def executeCMD(self ,command):
        exe_result  = os.system("@" + command.strip() + ">" + self.filename + " 2>nul"
        time.sleep(1)
        
    def run(self):
        try :
            command     = self.connection.recv(1024)
            print "receive command : %s" % (command)
            self.writelog('Receive command :' + command)

            if command == 'reboot' :
                exe_cmd = 'sc stop KeyCruiserServer '
                self.writelog('Execute command :' + exe_cmd )
                self.executeCMD(exe_cmd)
                time.sleep(2)
                exe_cmd = 'sc start KeyCruiserServer'
                self.writelog('Execute command :' + exe_cmd )
                self.executeCMD(exe_cmd)
            elif command == 'start' :
                exe_cmd = 'sc start KeyCruiserServer'
                self.writelog('Execute command :' + exe_cmd )
                self.executeCMD(exe_cmd)
            elif command == 'stop' :
                exe_cmd = 'sc stop KeyCruiserServer'
                self.writelog('Execute command :' + exe_cmd )
                self.executeCMD(exe_cmd)

            print "command has been executed"
            
            time.sleep(1)
            self.temp_file  = open(self.filename ,'r+')
            self.writelog('open file :' + self.filename )
            
            rst_list    = self.temp_file.readlines()
            result      = ""
            for i in rst_list:
                result += i
            self.connection.send(result)
            print "Result is sent to the client"
            
            self.CallBack(self)
        except socket.error , (errno, string):
            print 'Some errors happened %s :%s'  % (errno, string)
            self.writelog('Some errors happened ' ,errno, string )
            self.CallBack(self)
            
            
    def __del__(self):
        try :
            self.connection.close()
            del(self.connection)
            
            self.temp_file.close()
            del(self.temp_file)
            
            os.system("@del " + self.filename + " 2>nul"
            self.writelog("Delete temple file :" + self.filename)
            print "The KC thread finished"
        except AttributeError :
            pass


class TestRemoteServer(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestRemoteServer"
    _svc_display_name_ = "Test Remote Server"
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)

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


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


    def SvcDoRun(self):
        self.logfile = open('server.log' ,'a+')
        def CallBack(t):
            print "Enter Call Backup Function"
            t.__del__()
            del(t)
        
        
        def writelog(message):   
            self.logfile.write(time.asctime()+ "--" + message + '\n')
            self.logfile.flush()
        
        KCThreads = []
        inputs    = []
        inputs.append(self.server.local_socket)
   
        while(1):
            """
             "select" function does like a polling function
             its arguments respectively are "input , output , exceptions"
             the return value is a subset.
            """
            rs, ws, es = select.select(inputs, [], [] ,0)

            for r in rs:
                if r is self.server.local_socket:
                    (conn ,remote_client) = r.accept()
                    writelog("receive connection from %s port %s." % (remote_client[0] ,remote_client[1]))
                    print "receive connection from %s port %s." % (remote_client[0] ,remote_client[1])
#                    inputs.append(conn)
                    
                    KCThreads.append( OperateKCAsThread(conn ,self.logfile ,CallBack) )
                    writelog( "Thread object is created successfully" )
                    print "Thread object is created successfully"
                    
                    KCThreads[ len(KCThreads) -1 ].setDaemon(1)
                    KCThreads[ len(KCThreads) -1 ].start()
                    writelog( "begin to operate the server" )
                    print "begin to operate the server"
            
            self.timeout = 3000
            rc=win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
            if rc == win32event.WAIT_OBJECT_0:
                break

            time.sleep(3)
   
        
if __name__=='__main__':
    win32serviceutil.HandleCommandLine(TestRemoteServer)

论坛徽章:
0
发表于 2007-05-15 09:48 |显示全部楼层

已经解决!

在网上熬夜,终于找到了牛人HAM...写的setup.py 文件范例.
照方抓药, 搞定 .

PYTHON的水太深了, 难哪!

感谢各位的关注.

论坛徽章:
0
发表于 2007-05-15 22:20 |显示全部楼层
请问你是怎么实现的?
我那个也启动不了啊

论坛徽章:
0
发表于 2007-05-15 22:21 |显示全部楼层
程序如下:
import win32serviceutil
import win32service
import win32event

class test1(win32serviceutil.ServiceFramework):
    _svc_name_ = "test1"
    _svc_display_name_ = "test_python"
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        # Create an event which we will use to wait on.
        # The "service stop" request will set this event.
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        # Before we do anything, tell the SCM we are starting the stop process.
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # And set my event.
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        # We do nothing other than wait to be stopped!
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

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

错误是:服务没有及时响应启动或控制请求
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP