如何解决Python 3.3中的NameError: name 'threading'未定义?

12 投票
1 回答
40967 浏览
提问于 2025-04-18 01:14

我有一个程序,只有这个,使用的是Python 3.3。当我运行它的时候,我得到了

NameError: name 'threading' is not defined

我在网上搜索过,但没有找到能解释我情况的答案。有没有什么线索?谢谢!

#!/usr/bin/python

import Utilities
import os
import sys
import getopt
import time
from queue import Queue
from threading import Thread

_db_lock=threading.Lock()

我还尝试过

_db_lock=threading.Lock

1 个回答

25

你需要导入线程模块。把下面的代码加到你文件的开头:

import threading

错误出现在这一行:

_db_lock=threading.Lock()

这是因为你用了 from threading import Thread,但实际上你并没有把 threading 引入到本地命名空间里。所以现在只有 Thread 可用(虽然技术上说导入是成功的,但它并不在你的命名空间中,所以你不能使用它)。

如果你出于某种原因想要避免 threading 影响你的命名空间,可以像导入 Thread 一样导入 Lock,这样做:

from threading import Thread, Lock
_db_lock = Lock()

撰写回答