攻丝赢得';t调用函数(Python)
我有一个用python 2.7编写的脚本,它调用线程。但是,无论我做什么,线程都不会调用函数 它调用的函数:攻丝赢得';t调用函数(Python),python,multithreading,python-2.7,python-multithreading,Python,Multithreading,Python 2.7,Python Multithreading,我有一个用python 2.7编写的脚本,它调用线程。但是,无论我做什么,线程都不会调用函数 它调用的函数: def siren_loop(): while running: print 'dit is een print' 我试着这样称呼它: running = True t = threading.Thread(target=siren_loop) t.start() 或: 我甚至试着给siren_循环添加参数,看看这是否可行,但没有改变。我只是无法让它打印sir
def siren_loop():
while running:
print 'dit is een print'
我试着这样称呼它:
running = True
t = threading.Thread(target=siren_loop)
t.start()
或:
我甚至试着给siren_循环添加参数,看看这是否可行,但没有改变。我只是无法让它打印siren_循环函数中的行
我还尝试了许多其他奇怪的事情,但显然没有奏效。我做错了什么
编辑:因为人们说它有效,所以我尝试从另一个函数调用线程。所以它看起来像这样:
def start_sirene():
running = True
t = threading.Thread(target=siren_loop)
t.start()
然后这一部分被称为:
if zwaailichtbool == False:
start_sirene()
print 'zwaailicht aan'
zwaailichtbool = True
sleep(0.5)
也许这会引起问题?
最后一个语句中的print语句有效,当我在thread语句之前或之后添加print语句时,它也有效。
running
是代码中的局部变量。将全局运行
添加到start\u sirene()
因此,在尝试了数小时的各种事情后,我找到了解决方案,但仍然不理解问题所在
显然,程序不喜欢这么多步骤。我走了一步(启动警报器方法),但使用了完全相同的代码,突然它起了作用。我不知道为什么会有这个问题。如果有人知道,请告诉我xD它对我来说工作得非常好,您还可以将running指定为thread_函数的关键字参数
import threading
def siren_loop(running):
while running:
print 'dit is een print'
t = threading.Thread(target=siren_loop, kwargs=dict(running=True))
t.start()
我刚刚试过你的代码,使用你第一次尝试调用它的方式,它在
siren\u loop
中连续打印出你的语句。所以我不确定问题出在哪里。也使用QPython进行了验证。你的代码很好。我编辑了这个问题,把剩下的代码放在那里。也许zwaailichtbool
不是假的?创建线程后程序的其余部分做什么?如果它立即存在,线程将没有机会运行。还有,你是如何运作这一切的?您确定您有一个控制台,打印语句的输出应该放在这个控制台上吗?最后,您确定要用Python2.7运行它吗?因为当你用Python 3.x运行它时,线程只会因为语法错误而崩溃。这就是我所想的,但这不会给OP一个“未定义”的错误吗?你可能在其他地方初始化了全局运行。这不是问题所在。Running在我的代码开始时被初始化,它工作得很好。除非在Python中向函数添加global x
,否则x=something
将始终使其成为该函数的局部变量,即使在代码的其他地方有另一个x
。试试看:-)
import threading
def siren_loop(running):
while running:
print 'dit is een print'
t = threading.Thread(target=siren_loop, kwargs=dict(running=True))
t.start()