Python 中“很可能是由于循环导入”

Trq*_*qzy 7 python importerror

import threading
import time

start = time.perf_counter()

def do_something():
    print("Sleeping in 1 second")
    time.sleep(1)
    print("Done sleeping")

t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)

finish = time.perf_counter()
print(f"Finished in {round(finish-start,1)} seconds(s) ")
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么这段代码在运行时返回此错误以及如何修复它?

Traceback (most recent call last):
  File "c:/Users/amanm/Desktop/Python/Python Crash Course/threading.py", line 1, in <module>
    import threading
  File "c:\Users\amanm\Desktop\Python\Python Crash Course\threading.py", line 12, in <module>
    t1 = threading.Thread(target=do_something)
AttributeError: partially initialized module 'threading' has no attribute 'Thread' (most likely due to a circular import) 
Run Code Online (Sandbox Code Playgroud)

当我在正常 IDLE 中运行此代码时,它似乎可以工作,但在 Visual Studio Code 中不起作用。

len*_*ova 10

看起来您创建的程序文件名为threading.py,并且您正在导入一个也称为 的模块threading。这会导致循环导入,因为您的文件正在隐藏内置模块。

请重命名您的程序(例如,threading_example.py)。