在doctest中使用扭曲

时间:2015-11-16 08:03:10

标签: python twisted doctest

我在与doctest一起使用时遇到了麻烦。我正试图open a file这样:

from __future__ import print_function

from twisted.internet.defer import Deferred
from twisted.internet.fdesc import readFromFD, setNonBlocking
from twisted.internet.task import react


def asyncFunc(filename):
    """Description.

    Examples:
        >>> def run(reactor, filename):
        ...     d = asyncFunc(filename)
        ...     return d.addCallback(print)
        >>>
        >>> try:
        ...     react(run, ['hello.txt'])
        ... except SystemExit:
        ...     pass
        hello world
        <BLANKLINE>
    """
    with open(filename) as f:
        d = Deferred()
        fd = f.fileno()
        setNonBlocking(fd)
        readFromFD(fd, d.callback)
        return d

只使用一次测试就可以正常工作,但是对于多次测试,我得到ReactorNotRestartable错误。

def anotherAsyncFunc(filename):
    """Description.

    Examples:
        >>> def run(reactor, filename):
        ...     d = anotherAsyncFunc(filename)
        ...     return d.addCallback(print)
        >>>
        >>> try:
        ...     react(run, ['hello.txt'])
        ... except SystemExit:
        ...     pass
        hello world
        <BLANKLINE>
    """
    with open(filename) as f:
        d = Deferred()
        fd = f.fileno()
        setNonBlocking(fd)
        readFromFD(fd, d.callback)
        return d

然后我读了MemoryReactor并尝试了这个:

def anotherAsyncFunc(filename):
    """Description.

    Examples:
        >>> from twisted.test.proto_helpers import MemoryReactor
        >>> reactor = MemoryReactor()
        >>>
        >>> def run(reactor, filename):
        ...     d = anotherAsyncFunc(filename)
        ...     return d.addCallback(print)
        >>>
        >>> try:
        ...     react(run, ['hello.txt'], reactor)
        ... except SystemExit:
        ...     pass
        hello world
        <BLANKLINE>
    """
    with open(filename) as f:
        d = Deferred()
        fd = f.fileno()
        setNonBlocking(fd)
        readFromFD(fd, d.callback)
        return d

但这给了我一个'MemoryReactor' object has no attribute 'addSystemEventTrigger' AttributeError。有关正确方法的任何想法吗?

1 个答案:

答案 0 :(得分:0)

您已正确识别MemoryReactor未提供界面IReactorCore。正确的做法是将IReactorCore的实现贡献给MemoryReactor,以便第二个示例可以按预期工作。请打开一张票,然后这样做:)。