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

标签 python unit-testing ipython doctest

请帮助我获得一个嵌入式 ipython 控制台以在 doctest 中运行。示例代码演示了问题并将挂起您的终端。在 bash shell 上,我键入 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.IShellEmbed 在我的代码中使用 ipython 作为断点。这个技巧在我尝试过的任何地方都有效(在 django manage.py runserver 中,单元测试中),但它在 doctests 中不起作用。我认为这与 doctest 控制标准输入/标准输出有关。

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

最佳答案

我给 ipython 用户组发了邮件,得到了一些帮助。现在有一个 support ticket在未来的 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()

关于python - 如何在正在运行的 doctest 中使用 ipython 的 IPShellEmbed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1986805/

相关文章:

python - UTF-8 字符串作为字典中的键导致 KeyError

python - 我想抓取多个 div 内嵌套元素中的文本

java - Mockito 错误 : org. mockito.exceptions.misusing.InvalidUseOfMatchersException

angularjs - 控制如何处理 $httpBackend.when() 中的每个捕获

python - matplotlib 内联语法错误

python - 如何在 input() 正在进行时访问 input() 函数

python - 如何在 os.rename 中使用变量

c++ - boost 测试库: Multiple definition error

python - 将参数(目录)传递给 ipython 笔记本中的 %cd 命令

python - 当文件在磁盘上更改时自动重新加载 jupyter notebook