Python threads passing parameters

前端 未结 1 896
囚心锁ツ
囚心锁ツ 2021-02-10 16:51

I\'m trying to passing some parameter to the server tread, but I have no idea how?

this is my code:

HOST, PORT = socket.gethostbyname( socket.gethostname         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-10 17:50

    I think the second parameter of ThreadingTCPServer is a factory:

      SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )
    

    What you could do is your own factory here. Class will contstuct a callable object. when the object is called it will initialize MCRequestHandler with parameters given to the factory:

    class MyRequestHandlerFactory(object):
    
      def __init__(self, param1, param2): 
                self.param1 = param1
                self.param2 = param2
    
      def __call__(self):
                handler = MCRequestHandler()
                handler.param1 = param1
                handler.param2 = param2
    

    Then initialize:

      factory = MyRequestHandlerFactory("x", "y")
      SocketServer.ThreadingTCPServer( ( HOST, PORT ), factory)
    

    0 讨论(0)
提交回复
热议问题