请帮助我获得一个嵌入式 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/