2017-12-19 2 views
0

Der Versuch, zwei Methoden say_hello und say_world von getattr() in multiprocessing.Process aufzurufen, aber Methode say_world wurde nicht ausgeführt. Wie kann ich es möglich machen? Vielen Dank.Warum kann multiprocess.Process Aufruf getattr Methode nicht?

# -*- coding: utf-8 -*- 
from multiprocessing import Process 
import time 

class Hello: 
    def say_hello(self): 
     print('Hello') 

    def say_world(self): 
     print('World') 


class MultiprocessingTest: 
    def say_process(self, say_type): 
     h = Hello() 
     while True: 
      if hasattr(h, say_type): 
        result = getattr(h, say_type)() 
        print(result) 
      time.sleep(1) 

    def report(self): 
     Process(target=self.say_process('say_hello')).start() 
     Process(target=self.say_process('say_world')).start() # This line hasn't been executed. 


if __name__ == '__main__': 
    t = MultiprocessingTest() 
    t.report() 

Antwort

1

Der Parameter target erwartet einen Verweis auf eine Funktion als Wert aber Ihr Code übergibt None zu. Dies sind die notwendigen Teile zu ändern:

class Hello: 
    def say_hello(self): 
     while True: 
      print('Hello') 
      time.sleep(1) 

    def say_world(self): 
     while True: 
      print('World') 
      time.sleep(1) 

class MultiprocessingTest: 
    def say_process(self, say_type): 
     h = Hello() 
     if hasattr(h, say_type): 
      return getattr(h, say_type) # Return function reference instead of execute function 
     else: 
      return None 
+0

Diese Lösung funktioniert! Vielen Dank. Aber ich habe Zehner von 'say_xxx' Methode, in der die Häufigkeit von' time.sleep' nicht gleich ist. –

+1

Mit 'args' können Parameter an die Zielfunktionen übergeben werden:' Process (target = self.say_process ('say_hello'), args = (2,)). Start() 'wo musst du deine' say_xxx' deklarieren Methoden wie 'def say_xxx (self, sleep_time)'. – clemens

+0

Sie haben Recht. Ich werde den Schlaf in der Methode 'say_process' hinzufügen und die Methode' say_xxx' kann sich auf ihr eigenes Geschäft konzentrieren. –

Verwandte Themen