[英]Python threading: how to use return values of external scripts?
(I found a decent solution here for this, but unfortunately I'm using IronPython which does not implement the mutliprocessing module ...) (我在这里找到了一个不错的解决方案,但是不幸的是,我使用的是IronPython,它没有实现mutliprocessing模块...)
Driving script Threader.py will call Worker.py's single function twice, using the threading module. 驱动脚本Threader.py将使用线程模块两次调用Worker.py的单个函数。 Its single function just fetches a dictionary of data.
它的单一功能只是获取数据字典。
Roughly speaking: 粗略地说:
Worker.py 工人
def GetDict():
:
:
:
return theDict
Threader.py 线程器
import threading
from Worker import GetDict
:
:
:
def ThreadStart():
t = threading.Thread(target=GetDict)
t.start()
:
:
In the driver script Threader.py, I want to be able to operate on the two dictionaries outputted by the 2 instances of Worker.py. 在驱动程序脚本Threader.py中,我希望能够对Worker.py的2个实例输出的两个字典进行操作。
The accepted answer here involving the Queue module seems to be what I need in terms of accessing return values, but this is written from the point of view of everthing being doen in a single script. 就访问返回值而言, 这里涉及Queue模块的公认答案似乎是我所需要的,但这是从在单个脚本中完成所有工作的角度编写的。 How do I go about making the return values of the function called in Worker.py available to Threader.py (or any other script for that matter)?
如何使Worker.py中调用的函数的返回值可用于Threader.py(或与此相关的任何其他脚本)?
Many thanks 非常感谢
another way to do what you want (without using a Queue
) would be by using the concurrent.futures
module (from python3.2, for earlier versions there is a backport ). 另一种方法做你想要什么(不使用
Queue
)将通过使用concurrent.futures
模块(来自python3.2,为早期版本有一个补丁包 )。
using this, your example would work like this: 使用此示例,您的示例将如下所示:
from concurrent import futures
def GetDict():
return {'foo':'bar'}
# imports ...
# from Worker import GetDict
def ThreadStart():
executor = futures.ThreadPoolExecutor(max_workers=4)
future = executor.submit(GetDict)
print(future.result()) # blocks until GetDict finished
# or doing more then one:
jobs = [executor.submit(GetDict) for i in range(10)]
for j in jobs:
print(j.result())
if __name__ == '__main__':
ThreadStart()
edit: 编辑:
something similar woule be to use your own thread to execute the target function and save it's return value, something like this: 类似的事情是使用您自己的线程来执行目标函数并保存其返回值,如下所示:
from threading import Thread
def GetDict():
return {'foo':'bar'}
# imports ...
# from Worker import GetDict
class WorkerThread(Thread):
def __init__(self, fnc, *args, **kwargs):
super(WorkerThread, self).__init__()
self.fnc = fnc
self.args = args
self.kwargs = kwargs
def run(self):
self.result = self.fnc(*self.args, **self.kwargs)
def ThreadStart():
jobs = [WorkerThread(GetDict) for i in range(10)]
for j in jobs:
j.start()
for j in jobs:
j.join()
print(j.result)
if __name__ == '__main__':
ThreadStart()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.