首页 > 解决方案 > 使用线程时使用来自不同文件的变量时出错

问题描述

我目前在 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)

有想法该怎么解决这个吗?谢谢!

标签: pythonpython-3.x

解决方案


IISC 的问题是由于循环导入,即file2.py尝试从 导入某些东西file1.py,但为了file1.py阅读,它尝试从 导入file2.py。您可以尝试通过将gotime变量传递给main_taskas 参数来解决这个问题,如下所示:

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 threadingfile2.py因为它没有在那里使用。


推荐阅读