我无法理解以下代码中的执行流程。无法解释错误以及输出

时间:2017-12-30 20:38:22

标签: python-3.x runtime-error simpy

在下面的代码片段中,我试图理解这个简单的教程。我无法解释输出。我希望所有的" \ o /"在打印其他陈述之前一次打印。此外,回调存在问题。

    import simpy
    class School:
    def __init__(self, env):
        self.env = env
        self.class_ends = env.event()
        self.pupil_procs = [env.process(self.pupil()) for i in range(3)]
        for x in self.pupil_procs:
            x.callbacks.append(self.my_callback(x))
            #print(x.callbacks)

        self.bell_proc = env.process(self.bell())

    def bell(self):
        for i in range(2):
            value=yield self.env.timeout(45,value="bell_rang!at"+str(env.now))
            self.class_ends.succeed(value='class_ends!')
            print("in bell proc")
            self.class_ends = self.env.event()
            print(value)


    def pupil(self):
        for i in range(2):
            print(' \o/',i, end=' ')
            classends=yield self.class_ends
            print('done!')
            print(classends)

    def my_callback(self,event):
        print('Called back from',event)


env = simpy.Environment()
school = School(env)
env.run()

输出如下:

Called back from <Process(pupil) object at 0x7fd7ddce97b8>
Called back from <Process(pupil) object at 0x7fd7ddce9be0>
Called back from <Process(pupil) object at 0x7fd7ddcad5f8>
 \o/ 0  \o/ 0  \o/ 0 in bell proc
bell_rang!at0
done!
class_ends!
 \o/ 1 done!
class_ends!
 \o/ 1 done!
class_ends!
 \o/ 1 in bell proc
bell_rang!at45
done!
class_ends!
done!
class_ends!
done!
class_ends!
Traceback (most recent call last):
  File "/home/deeplearning/PycharmProjects/python-scheduling/learnSimPy/learnmore.py", line 35, in <module>
    env.run()
  File "/usr/local/lib/python3.5/dist-packages/simpy/core.py", line 137, in run
    self.step()
  File "/usr/local/lib/python3.5/dist-packages/simpy/core.py", line 221, in step
    callback(event)
TypeError: 'NoneType' object is not callable

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

您将self.my_callback(x)None)的结果添加到回调列表中。

相反,您应该附加functools.partial(self.my_callback, x)

我还建议您使用yield from process而不是将函数追加到process的回调中。