dbr*_*dbr 4 python user-interface read-eval-print-loop
大量示例Python代码显示了Python REPL的输出,例如:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
现在,您要做的显而易见的事情就是运行上面的代码..所以,我运行"python"并将上面的文本粘贴到..
>>> >>> class eg(object):
File "<stdin>", line 1
>>> class eg(object):
^
SyntaxError: invalid syntax
>>> ... def __init__(self, name):
File "<stdin>", line 1
... def __init__(self, name):
^
Run Code Online (Sandbox Code Playgroud)
代码坏了!?..
为了让它运行,我将不得不..
>>>和...,然后再粘贴这不是一个大问题,但考虑到以这种格式呈现了多少示例代码,看起来很奇怪你必须这样做.
使用IPython shell
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
Run Code Online (Sandbox Code Playgroud)使用功能强大的文本编辑器(例如,C-x r k杀死Emacs中的矩形区域)
使用doctest模块
首先没有shell提示复制(例如,我不知道如何在Google Chrome上执行此操作).
将以下内容保存到documentation.txt:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
>>> 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
>>>
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
跑:
$ python -c "import doctest; doctest.testfile('documentation.txt')" -v
Run Code Online (Sandbox Code Playgroud)
输出:
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.
Run Code Online (Sandbox Code Playgroud)
如果您在模块的末尾添加以下代码段,它将测试其文档字符串中的所有代码:
if __name__=="__main__":
import doctest; doctest.testmod()
Run Code Online (Sandbox Code Playgroud)
QED
| 归档时间: |
|
| 查看次数: |
326 次 |
| 最近记录: |