python - 使用线程时使用来自不同文件的变量时出错
问题描述
我目前在 2 个 python 文件中有 2 个函数。第一个看起来像(称为file1.py)
import threading
from file2 import main_task
gotime = threading.Event()
thread1 = threading.Thread(target=main_task)
thread1.start()
input()
gotime.set()
第二个(file2.py)看起来像:
import threading
def main_task():
print('Waiting!')
gotime.wait()
print('Event has bet triggered!')
现在当我运行它时,我得到
NameError: name 'gotime' is not defined
所以我尝试通过将 gotime 导入 file2py 来修复它,如下所示:
from file1 import gotime
但是在运行之后,我得到了
ImportError: cannot import name 'main_task' from 'file2' (/my/dir/file2.py)
有想法该怎么解决这个吗?谢谢!
解决方案
IISC 的问题是由于循环导入,即file2.py
尝试从 导入某些东西file1.py
,但为了file1.py
阅读,它尝试从 导入file2.py
。您可以尝试通过将gotime
变量传递给main_task
as 参数来解决这个问题,如下所示:
file1.py
:
import threading
from bar import main_task
gotime = threading.Event()
thread1 = threading.Thread(target=main_task, args=(gotime,))
thread1.start()
input()
gotime.set()
file2.py
:
def main_task(gotime):
print('Waiting!')
gotime.wait()
print('Event has bet triggered!')
请注意,我跳过了它import threading
,file2.py
因为它没有在那里使用。
推荐阅读
- flutter - 如何从颤振应用程序中投射屏幕?
- python - 如何使用线程更新 tkinter gui 标签?
- html - 如何使一端有滚动的模态框的角变圆
- flutter-provider - 在颤动中使用数据库提供者模式
- r - R 控制台和笔记本中的奇怪字符
- python - 如何使用 ReportLab 在 PDF 中绘制电子签名
- openwhisk - OpenWhisk 是否支持 OpenAPI 3.x 规范?
- css - 使用 Jekyll / Hugo 站点的自托管 Nginx 未加载 CSS
- google-apps-script - 添加 OAUTH 范围时如何不执行“onAddToSpace”
- swift - 为什么具有 autosaveExpandedItems true 的基于视图的 NSOutlineView 在 reloadData 时忽略扩展?