从本地程序包调用时,Python多处理类失败

时间:2016-08-31 15:28:28

标签: python-3.x ipython packages python-multiprocessing

我试图编写一个包含一个使用多处理包的类的包。我将使用一个打印出来的类#34; Hello,person",其中person是字符串数组中的元素,以说明问题。

class Hello:
    def __init__(self, people):
        self.people = people

    class _task(object):
        def __init__(self, person):
            self.person = person

        def __call__(self):
            self.greet(self.person)

        def greet(self, person):
            print('Hello, {}'.format(person))

    class _consumer(mp.Process):
        def __init__(self, task_queue, result_queue):
            mp.Process.__init__(self)
            self.task_queue = task_queue
            self.result_queue = result_queue

        def run(self):
            while True:
                next_task = self.task_queue.get()
                if next_task is None:
                    # poison pill
                    self.task_queue.task_done()
                    break
                answer = next_task()
                self.task_queue.task_done()
                self.result_queue.put(answer)

    def greet(self):
        # establish communication queues
        tasks = mp.JoinableQueue()
        results = mp.Queue()

        # start consumers
        num_consumers = len(self.people)
        consumers = [self._consumer(tasks, results)
                     for ii in range(num_consumers)]
        for w in consumers:
            w.start()

        # enqueue jobs
        for person in self.people:
            tasks.put(self._task(person))

        # add a poison pill for each consumer
        for ii in range(num_consumers):
            tasks.put(None)

        # wait for tasks to finish
        tasks.join()

这个主要脚本是test.py:

import hello

if __name__ == '__main__':
    people = ['Alice', 'Bob', 'Clarissa', 'David', 'Elizabeth', 'Frank',
              'Gertrude', 'Harry']
    hi = hello.Hello(people)
    hi.greet()

包当前是一个文件夹的一部分,并且排列在一个层上。

hello/
    __init__  # from .hello_world import Hello
    hello_world.py  # contains class
test.py

如果我从python控制台运行脚本test.py,我得到了我期望的输出:

Hello, Alice
Hello, Bob
Hello, Clarissa
Hello, David
Hello, Elizabeth
Hello, Frank
Hello, Gertrude
Hello, Harry

如果我尝试从ipython控制台运行test.py,它会挂起并且内核显示错误

ImportError: No module named 'hello'

如果我将类复制到test.py的顶部,只导入多处理并从python控制台或ipython控制台运行,那么我得到正确的输出。

我在Windows 7上运行64位python 3.您可以在my github找到该包。

为什么这不能在ipython控制台中运行?

0 个答案:

没有答案