Python ImportError: Cannot import name 'Empty'

  • 问题: 在验证线程池创建示例中,通过执行以下代码,频繁提示无法Import Empty模块。代码示例如下:
from multiprocessing import Pool
import os
import time
import random


def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__ == '__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(4)
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')

  • 表现:程序编译错误,显示无法引入相关模块。

Python ImportError: Cannot import name 'Empty'_第1张图片


  • 问题根源:

      Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default. This allows Python programs that know what they’re doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported.

首先确定该文件名避免与引入模块同名,其次检查编译脚本目录下是否有和python自带模块名称一致的.py文件,这会导致python的引用错误。


  • 预期结果:

Python ImportError: Cannot import name 'Empty'_第2张图片

你可能感兴趣的:(实用技能)