A feature of the doctest module can be useful when people copy and paste their idle window in the python forum: the ability to transform an example from the python interpreter into python code without the prompts >>>, ...
and the output messages. The script below permits to use this function from the command line.
Convert python examples to runnable code.
TrustyTony commented: Handy +13
HiHe commented: neat +5
# script_from_examples.py
""" Script to convert python interpreter examples into python code
Usage:
python script_from_examples.py <file>
read a file containing python interpreter examples and outputs
the python code without the prompt. For example if <file> contains
>>> L = range(3)
>>> for x in L:
... print x
...
0
1
2
>>>
the output of the command in stdout will be the python code
L = range(3)
for x in L:
print x
# Expected:
## 0
## 1
## 2
"""
import doctest
import sys
if __name__ == "__main__":
assert len(sys.argv) == 2
filename = sys.argv[-1]
print doctest.script_from_examples(open(filename).read())
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.