使用concurrent.futures
从多个文本文件中读取时发现了一个奇怪的错误。
这是一个可重复的小例子:
import os
import concurrent.futures
def read_file(file):
with open(os.path.join(data_dir, file),buffering=1000) as f:
for row in f:
try:
print(row)
except Exception as e:
print(str(e))
if __name__ == '__main__':
data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
files = ['file1', 'file2']
with concurrent.futures.ProcessPoolExecutor() as executor:
for file,_ in zip(files,executor.map(read_file,files)):
pass
file1
和file2
是data
目录中的任意文本文件。
我收到以下错误(基本上一个进程在分配之前尝试读取data_dir
变量):
concurrent.futures.process._RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\process.py", line 175, in _process_worker
r = call_item.fn(*call_item.args, **call_item.kwargs)
File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\process.py", line 153, in _process_chunk
return [fn(*args) for args in chunk]
File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\process.py", line 153, in <listcomp>
return [fn(*args) for args in chunk]
File "C:\Users\my_username\Downloads\example.py", line 5, in read_file
with open(os.path.join(data_dir, file),buffering=1000) as f:
NameError: name 'data_dir' is not defined
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "example.py", line 16, in <module>
for file,_ in zip(files,executor.map(read_file,files)):
File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\_base.py", line 556, in result_iterator
yield future.result()
File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\_base.py", line 405, in result
return self.__get_result()
File "C:\Users\my_username\AppData\Local\Continuum\Anaconda3\lib\concurrent\futures\_base.py", line 357, in __get_result
raise self._exception
NameError: name 'data_dir' is not defined
如果我在data_dir
块之前放置if __name__ == '__main__':
赋值,我不会收到此错误,代码会按预期执行。
导致此错误的原因是什么?显然,在两种情况下都应该进行异步调用之前分配data_dir
。
答案 0 :(得分:3)
ProcessPoolExecutor
会产生一个新的Python 进程,导入正确的模块并调用您提供的功能。
由于data_dir
仅在您运行模块时定义,而不是在您导入时定义,因此会出现错误。
将data_dir
文件描述符作为参数提供给read_file
可能工作,因为我相信进程会继承其父项的文件描述符。不过,你需要检查一下。
如果要使用ThreadPoolExecutor
,那么您的示例应该可以正常工作,因为生成的线程共享内存。
答案 1 :(得分:2)
fork()
在Windows上不可用,所以python使用spawn
来启动新进程,这将启动一个新的python解释器进程,没有内存将被共享,但python将try to recreate worker新流程中的功能环境,这就是模块级变量工作的原因。请参阅doc for more detail。