我可以导入一个与标准库同名的本地模块吗?

Can I import a local module with the same name as a standard-library one?

我创建了自己的名为 queue 的模块,并且正在尝试导入它。但是,在尝试使用它时,出现错误 'Queue' object has no attribute 'enqueue'

如何导入我自己的队列(enqueue),而不是标准库队列(没有)?

def driver():
    import queue
    q = queue.Queue()
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
            print("The prority of the job is: " + new_item.job_priority)
            print("The job type is: " + new_item.job_type)

试试这个:

from queue import *

q = Queue ()

def driver():
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
            print("The prority of the job is: " + new_item.job_priority)
            print("The job type is: " + new_item.job_type)

我认为问题在于 python 正在导入它的内置模块队列,因此在实例化队列 class 时,您正在创建 pthon 内置类型队列的对象。

解决此问题的方法是更改​​模块和 class 名称,在 python 中创建具有相同名称的函数、模块或 class 时有此约定name 作为内置函数、模块或名称是你应该在你自己的模块的末尾添加一个 _ 和 class,

所以,可以试试

 queue ==> queue_
 Queue ==> Queue_ 

在 Python 2.x 中,您可以通过在任何其他导入之前添加以下行来消除本地 queue 和标准库之间的歧义:

from __future__ import absolute_import

...然后使用:

import .queue as local_queue
q = local_queue.Queue()

...获得您自己的实现,而不是标准实现。


在 Python 3 中,此行为是默认行为,因此您不需要 from __future__ import 即可使用 import .queuequeue.py 显式导入在与当前代码相同的包或目录中。

将您的内部文件重命名为 my_queue.py 之类的名称,然后像这样将其导入到您的文件中。这避免了像 from queue import * 这样的不良做法以及与标准库的名称冲突,这很可能是您现在 运行 遇到的问题。

import my_queue

def driver():
    q = my_queue.Queue()
    for line in df:
        if 'received' in line:
            q.enqueue(line)
            print("Adding job " + new_item.job_ID + " to the queue with the timestamp: " + new_item.time_stamp + ".")
            print("The prority of the job is: " + new_item.job_priority)
            print("The job type is: " + new_item.job_type)