Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:如何实时从调用函数中获取结果?_Python_Multithreading_Call - Fatal编程技术网

python:如何实时从调用函数中获取结果?

python:如何实时从调用函数中获取结果?,python,multithreading,call,Python,Multithreading,Call,我想做的是实时从调用函数中获取结果。 例如,我希望实时获取类内模型的I结果,但是如果使用return,则只能获取I一次结果 import threading class model(object): """docstring for model""" def __init__(self): pass def func(self): for i in range(1000): print('i',i)

我想做的是实时从调用函数中获取结果。 例如,我希望实时获取类内模型的
I
结果,但是如果使用return,则只能获取
I
一次结果

import threading

class model(object):
    """docstring for model"""
    def __init__(self):
        pass


    def func(self):  
        for i in range(1000):
            print('i',i)
            return i

class WorkThread(threading.Thread):  
    # trigger = pyqtSignal()  
    def __int__(self):  
        super(WorkThread,self).__init__()  

    def run(self):  
        model1=model()
        result = model1.func() #I want to get `i` from class model in real time,however return can only get once.
        print('result',result)

if __name__ == '__main__':
    WorkThread=WorkThread()
    WorkThread.start()
    for j in range(1000,2000):
        print('j',j)

有人有好主意吗?希望能得到帮助。

你有几个选择;你可以:

  • 使用生成器函数,在迭代时生成结果。这要求
    model1.func()
    调用在
    model1.func()调用返回的生成器上循环。如果不需要从其他线程访问数据,请使用此选项

  • 使用队列;在生成结果时将
    i
    结果推送到队列中,另一个线程可以从队列中接收它们