我正在玩扭曲,我正在尝试创建一个简单的主服务器,它将单元测试列表分发给它的从属服务器。以下代码有效,但我的输出很奇怪。从站执行最后一次单元测试n次,而不是执行n次测试中的每一项。
我正在使用twisted的内置放大器协议。以下是相关代码:
class Master(object):
def __init__(self):
self.tests = [
"test1",
"tests2",
... etc
]
def serve(self):
self.factory = MasterFactory()
reactor.listenTCP(1234, self.factory)
d = threads.deferToThread(self.get_cmd)
d.addCallback(lambda ign: self.run_test())
print 'Serving on port 1234'
def get_cmd(self):
return raw_input('> ')
def run_test(self):
while True:
for slave in self.factory.slaves.values():
if self.tests == []:
break
slave.tests.append(self.tests.pop(0))
if self.tests == []:
break
for slave in self.factory.slaves.values():
self.construct_list(slave)
def construct_list(self, slave):
d = defer.Deferred()
for test in slave.tests:
d.addCallback(lambda ign:
slave.protocol.callRemote(commands.RunCmd, cmd="python setup.py trial -s " + test))
d.addCallback(self.cmd_response)
d.callback(None)
def cmd_response(self, response):
print response['output']
return None
def main():
m = Master()
m.serve()
reactor.run()
if __name__ == "__main__":
main()
答案 0 :(得分:3)
这是循环变量和闭包在Python中如何工作的常见问题。考虑这个例子:
>>> def f(n):
... print n
...
>>> fs = []
>>> for i in range(3):
... fs.append(lambda: f(i))
...
>>> fs[0]()
2
>>> fs[1]()
2
>>> fs[2]()
2
>>>