如何运行/采用“Pythons REPL 的输出”
使用IPython外壳
In [99]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:>>> class eg(object):
:... def __init__(self, name):
:... self.name = name
:... def hi(self):
:... print "Hi %s" % (self.name)
:...
:>>> greeter = eg("Bob")
:>>> greeter.hi()
:--
Hi Bob
使用功能强大的文本编辑器(例如,在EmacsC-x r k
中删除矩形区域)
使用doctest模块
首先在没有 shell 提示的情况下进行复制(例如,尽管我不知道如何在 Google Chrome 上执行此操作)。
为什么使用 doctest 格式
将以下内容保存到documentation.txt
:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua。Ut enim 广告
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat。
>>> 类例如(对象):
... def __init__(self, name):
... self.name = 名称
...定义嗨(自我):
... 打印 "Hi %s" % (self.name)
...
>>> 迎接者 = 例如(“鲍勃”)
>>> 迎接者.hi()
嗨鲍勃
>>>
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur。Exceptioneur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
产房。
跑:
$ python -c "import doctest; doctest.testfile('documentation.txt')" -v
输出:
Trying:
class eg(object):
def __init__(self, name):
self.name = name
def hi(self):
print "Hi %s" % (self.name)
Expecting nothing
ok
Trying:
greeter = eg("Bob")
Expecting nothing
ok
Trying:
greeter.hi()
Expecting:
Hi Bob
ok
1 items passed all tests:
3 tests in doctest.txt
3 tests in 1 items.
3 passed and 0 failed.
Test passed.
如果您在模块末尾添加以下代码段,它将测试其文档字符串中的所有代码:
if __name__=="__main__":
import doctest; doctest.testmod()
QED