python - 如何从线程执行的函数中获取值?
问题描述
我有 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)
它是有效的,但是我一个接一个地运行脚本实例,而不是同时运行。
有人知道如何处理吗?:)
解决方案
首先,如果您在 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)
推荐阅读
- python - 以自定义格式将 Pandas 数据框导出为 CSV
- unity3d - 如果对象不移动,onTriggerEnter2D 只会触发一次
- html - CSS 位置:根据“html”和“body”标签的溢出值在不同浏览器中出现奇怪的行为
- java - java中的松树与for循环
- reactjs - 如何防止用户在使用 jsx 的表单中粘贴特定的特殊字符(仅允许的字符包括 (_ - .)
- jquery - SVG 中的 jQuery .offset() 在 Safari 中不起作用
- python - Twilio 在接收短信时触发 Python 函数
- javascript - 如何从总数中启动复选框组值
- android - 编译未能完成:程序类型已存在:com.google.android.gms.ads.identifier.AdvertisingIdClient$zza
- python - '12/2/14 0:01' 形式的字符串的正确 pd.to_datetime 格式是什么?