[英]Python thread not setting output variable
So I have a simple thread that goes and performs an http request that returns a json object and I want to use json.loads to put that in to a dict specified by passing a reference to said dict. 所以我有一个简单的线程去执行一个返回json对象的http请求,并且我想使用json.loads将其放入通过传递对dict的引用而指定的dict中。
def thr_get_json(host, port, path, result):
conn = httplib.HTTPConnection(host, port)
conn.request('GET', path)
resp = conn.getresponse()
if resp.status != 200:
raise "HTTP Error!"
result = json.loads(resp.read())
results = {}
get_thread = threading.Thread(target=thr_get_json, args=('example.com', 80, '/output.php', results))
For some reason, results is empty. 由于某种原因,结果为空。 As it's a mutable object being passed to a function then it would be a reference right? 由于它是一个可变对象,将被传递给函数,因此它是引用权吗? Or am I way out on this. 还是我要解决这个问题。
You must use result.update() 您必须使用result.update()
You just overwrote result, it's a different variable like that 您只是重写了结果,这是一个不同的变量
(attention to the fact that you use both result (singular) and results) (注意您同时使用结果(单数)和结果)
You Need to pass a Key as-well, or define a key where you would store your result: 您还需要传递一个Key或定义一个将结果存储在其中的密钥:
Inside your function append the data to the dict: result['responseData'] = json.loads(resp.read()) 在函数内部,将数据追加到字典:result ['responseData'] = json.loads(resp.read())
you can access the results by using the results['responseData'] after the thread executes 您可以在线程执行后使用result ['responseData']访问结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.