首页 > 解决方案 > 如何从线程执行的函数中获取值?

问题描述

我有 main_script.py ,它导入从网页获取数据的脚本。我想通过使用多线程来做到这一点。我想出了这个解决方案,但它不起作用:

主脚本:

import script1
temp_path = ''
thread1 = threading.Thread(target=script1.Main,
                             name='Script1',
                             args=(temp_path, ))

thread1.start()
thread1.join()

脚本1:

class Main:
    def __init__()
    def some_func()
    def some_func2()

    def __main__():
        some_func()
        some_func2()
        return callback

现在只有一种方法我知道从 script1 到 main_script 的回调值是:

主脚本:

import script1
temp_path = ''
# make instance of class with temp_path
inst_script1 = script1.Main(temp_path)

print("instance1:")
print(inst_script1.callback)

它是有效的,但是我一个接一个地运行脚本实例,而不是同时运行。

有人知道如何处理吗?:)

标签: pythonmultithreadingreturn

解决方案


首先,如果您在 Python 中使用线程,请确保您阅读:https ://docs.python.org/2/glossary.html#term-global-interpreter-lock 。除非您使用 C 模块或大量 I/O,否则您不会看到脚本同时运行。一般来说,multiprocessing.pool是一种更好的方法。

如果您确定我们需要线程而不是进程,您可以使用可变变量来存储结果。例如,一个记录每个线程结果的字典。

result = {}

def test(val, name, target):
   target[name] = val * 4 

temp_path = 'ASD'
thread1 = threading.Thread(target=test,
                             name='Script1',
                             args=(temp_path, 'A', result))

thread1.start()
thread1.join()
print (result)

推荐阅读