1

True我需要一个简单的类或函数,它接受一个测试(返回or的可调用对象False)和一个在测试时调用的函数True,可能在不同的线程中完成整个事情。像这样的东西:

nums = []
t = TestClass(test=(lambda: len(nums) > 5),
              func=(lambda: sys.stdout.write('condition met'))

for n in range(10):
    nums.append(n)
    time.sleep(1) 

#after 6 loops, the message gets printed on screen.

任何帮助表示赞赏。(拜托,不要太复杂,因为我还是初学者)

4

2 回答 2

1

您认为您可能需要一个单独的线程来检查后台条件是正确的。在这个单独的线程中,您还必须决定要检查的频率(还有其他方法可以做到这一点,但这种方式需要对您显示的代码进行最少的更改)。

我的回答只是使用一个函数,但如果你愿意,你可以轻松地使用一个类:

from threading import Thread
import time
import sys    

def myfn(test, callback):

    while not test():  # check if the first function passed in evaluates to True
        time.sleep(.001)  # we need to wait to give the other thread time to run.
    callback() # test() is True, so call callback.

nums = []

t = Thread(target=myfn, args=(lambda: len(nums) > 5, 
           lambda: sys.stdout.write('condition met')))
t.start() # start the thread to monitor for nums length changing

for n in range(10):
    nums.append(n)
    print nums  # just to show you the progress
    time.sleep(1) 
于 2012-05-23T21:13:33.500 回答
0

不完全确定您在问什么,但我认为这应该可以帮助您入门。

def test_something(condition, action, *args, **kwargs):
  if condition():
    action(*args, **kwargs)

def print_success():
  print 'Success'

def test_one():
  return True

test_something(test_one, print_success)
于 2012-05-23T20:59:52.430 回答