python-如何获取Timer中使用的函数的输出 [英] python- how to get the output of the function used in Timer

查看:63
本文介绍了python-如何获取Timer中使用的函数的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行一个函数 10 秒然后做其他事情.这是我使用 Timer 的代码

I want to run a function for 10s then do other stuff. This is my code using Timer

from threading import Timer
import time

def timeout():
    b='true'
    return b

a='false'    
t = Timer(10,timeout)
t.start()

while(a=='false'):
    print '1'
    time.sleep(1)
print '2'

我知道使用 Timer 我可以在计时器结束时打印一些东西(打印 b 而不是 return b 在 10 秒后返回 true).我想知道的是:我可以在a"中获取 timeout() 返回的值以正确执行我的 while 循环吗?

I know that using Timer I can print something at the end of the timer (print b instead of return b return true after 10s). What I want to know is : can I get the value returned by timeout() inside "a" to perform my while loop correctly?

或者有其他方法可以用另一个函数来做吗?

Or is there another way to do it with another function ?

推荐答案

函数的返回值只是被Timer删除了,正如我们在.解决这个问题的一种方法是传递一个可变参数并在函数内部对其进行变异:

The return value of the function is just dropped by Timer, as we can see in the source. A way to go around this, is to pass a mutable argument and mutate it inside the function:

def work(container):
    container[0] = True

a = [False]
t = Timer(10, work, args=(a,))
t.start()

while not a[0]:
    print "Waiting, a[0]={0}...".format(a[0])
    time.sleep(1)

print "Done, result: {0}.".format(a[0])

或者,使用global,但这不是绅士的做法.

Or, use global, but that's not the way a gentleman goes.

这篇关于python-如何获取Timer中使用的函数的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆