如何在运行的doctest中使用ipython的IPShellEmbed

3 投票
1 回答
1436 浏览
提问于 2025-04-15 17:31

请帮我在doctest中运行一个嵌入式的ipython控制台。示例代码展示了这个问题,并且会让你的终端卡住。在bash终端中,我需要按ctrl-Z,然后用kill %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.Shell.IPShellEmbed把ipython当作代码中的一个断点来使用。这个技巧在我尝试过的所有地方都有效(比如在django的manage.py runserver中,或者单元测试中),但在doctest中就不行了。我觉得这可能和doctest控制输入输出有关。

提前谢谢你的帮助。 - Philip

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()

撰写回答