python - 如何使用线程读取文件内容并存储在局部变量中?
问题描述
我需要在线程中读取文件并将文件中存在的数据存储在局部变量中(在脚本中存在于线程之外的变量)。我将此变量作为参数发送到线程。如果我没有读取文件,而只是访问变量,那么一切正常。但是如果我正在读取一个文件,那么变量(这里是字典)就会出现空。我不确定为什么会这样。请让我知道为什么会发生这种情况以及我能做些什么。谢谢。
(我在 Windows 10 上使用 python 3.9.6)
import threading
import time
import os
def thread_function(filename: str, line_dict: dict, lock:threading.Lock):
lock.acquire(blocking=True, timeout=5.8)
with open(filename, 'r') as f:
for id,line in enumerate(f):
line_dict['line{}'.format(id)] = line
lock.release()
print('[from thread] Keys in Dictionary: \n{}'.format(line_dict.keys()))
line_dict = {}
lock = threading.Lock()
if __name__ == '__main__':
t = threading.Thread(target=thread_function, args=('./lines.txt', line_dict, lock))
t.start()
print('[from main] Keys in Dictionary: \n{}'.format(line_dict.keys()))
t.join()
解决方案
推荐阅读
- reactjs - 如何返回具有递增或递减值的 redux 状态?
- php - xhttp.send() 命令,“被 CORS 策略阻止:仅支持跨源请求......”等
- php - 将 Strtotime('now') 拆分为秒和分钟
- gnuplot - 与 gnuplot 格式说明符 %t 和 %T 不一致?
- python - python-docx 为每个段落设置不同的样式
- pdfbox - 遍历 PDF 文件上的文本对象/框/标签
- amazon-web-services - IntelliJ Dockerfile 运行/调试配置:如何添加本地 AWS 凭证?
- android - Android 应用程序上下文配置不会使用新的语言环境进行更新
- excel - Excel:基于输入的数字动态列表
- visual-studio - 如何更改 VS 中的参数信息工具提示颜色