Python Threading传递含列表的多参数失败,请求排查问题
问题描述
需要在指定超时时间内解析/opt/data/路径下生成的若干JSON文件,将其中topic字段匹配预期列表的JSON数据存入队列。但编写代码后无法将expect_topics列表作为args参数传递给线程的json_parse函数,尝试kwargs也未解决,原代码如下:
import time, Path, threading, queue monitor_result = queue.Queue json_path= Path("/opt/data/") json_files = set(json_path.rglob("*.json")) expect_topics = ["aaa", "bbb"] def json_parse(time_out: int, topics : list, result: queue.Queue): while time_out > 0: result_list = [] for file in json_files: with file.open() as f: temp = json.load(f) if temp['topic'] in topics: result_list.append(temp) result.put(result_list) time.sleep(1) time_out -= 1 # in 5s, parsing all json files content to monitor_result # if json file have value of key "topic" matching list expect_topics monitor_thread = threading.Thread( target=json_parse, args=(5, expect_topics, monitor_result) ) monitor_thread.start() time.sleep(1) monitor_thread.join() json_data_list = monitor_result.get() print(json_data_list)
错误分析
- 队列未实例化:
monitor_result = queue.Queue仅引用了队列类,没有创建实例对象,正确写法应为monitor_result = queue.Queue()。传参时传递类而非实例,会导致后续调用get()、put()方法时出错。 - 缺失json模块导入:代码中使用
json.load(f)但未导入json模块,运行时会触发NameError。 - 语法缩进错误:
json_parse函数内,with file.open() as f:后的代码没有缩进,Python依赖缩进划分代码块,这会直接引发语法错误。 - 文件集合未动态更新:
json_files = set(json_path.rglob("*.json"))仅在初始化时获取一次文件列表,超时循环中不会检测新生成的JSON文件,不符合“路径下会生成若干JSON文件”的需求。 - 传参误解:实际上
expect_topics列表本身可以正常传递,代码运行失败是由上述其他错误导致,并非列表传参的问题。
修正后的代码
import time from pathlib import Path import threading import queue import json # 实例化队列对象 monitor_result = queue.Queue() json_path = Path("/opt/data/") expect_topics = ["aaa", "bbb"] def json_parse(time_out: int, topics: list, result: queue.Queue): remaining_time = time_out while remaining_time > 0: result_list = [] # 每次循环重新获取当前目录下的所有JSON文件,适配新生成的文件 json_files = set(json_path.rglob("*.json")) for file in json_files: try: with file.open("r") as f: temp = json.load(f) # 先判断topic键是否存在,避免KeyError if "topic" in temp and temp["topic"] in topics: result_list.append(temp) except json.JSONDecodeError: print(f"文件{file}不是合法JSON格式,跳过") except Exception as e: print(f"处理文件{file}时出错: {str(e)}") if result_list: result.put(result_list) time.sleep(1) remaining_time -= 1 # 启动线程,传递参数 monitor_thread = threading.Thread( target=json_parse, args=(5, expect_topics, monitor_result) ) monitor_thread.start() # 等待线程执行完毕 monitor_thread.join() # 取出队列中所有数据 while not monitor_result.empty(): json_data_list = monitor_result.get() print(json_data_list)
内容的提问来源于stack exchange,提问作者Hung Nguyen
相关产品推荐
相关产品推荐

