3

请帮助我获得一个嵌入式 ipython 控制台以在 doctest 中运行。示例代码演示了该问题并将挂起您的终端。在 bash shell 上,我键入 ctrl-Z 然后杀死 %1 以突围并杀死,因为 ctrl-C 不起作用。

def some_function():
    """
    >>> some_function()
    'someoutput'
    """
    # now try to drop into an ipython shell to help 
    # with development
    import IPython.Shell; IPython.Shell.IPShellEmbed(argv=[])()
    return 'someoutput'

if __name__ == '__main__':
    import doctest
    print "Running doctest . . ."
    doctest.testmod()

我喜欢使用 ipython 来帮助编写代码。一个常见的技巧是在我的代码中使用 ipython 作为断点,方法是调用IPython.Shell.IPShellEmbed. 这个技巧在我尝试过的任何地方都有效(在 django manage.py runserver、单元测试中),但它在 doctests 中不起作用。我认为这与 doctest 控制标准输入/标准输出有关。

在此先感谢您的帮助。- 菲利普

4

1 回答 1

0

我给 ipython 用户组发了邮件,得到了一些帮助。现在有一张支持票可以在 ipython 的未来版本中修复此功能。这是一个带有解决方法的代码片段:

import sys

from IPython.Shell import IPShellEmbed

class IPShellDoctest(IPShellEmbed):
   def __call__(self, *a, **kw):
       sys_stdout_saved = sys.stdout
       sys.stdout = sys.stderr
       try:
           IPShellEmbed.__call__(self, *a, **kw)
       finally:
           sys.stdout = sys_stdout_saved


def some_function():
  """
  >>> some_function()
  'someoutput'
  """
  # now try to drop into an ipython shell to help
  # with development
  IPShellDoctest()(local_ns=locals())
  return 'someoutput'

if __name__ == '__main__':
  import doctest
  print "Running doctest . . ."
  doctest.testmod()
于 2010-01-06T08:12:53.257 回答