954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Convert python examples to runnable code.

By Gribouillis on Jul 14th, 2011 12:03 am

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.

# 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())

Looks like the doctest can not handle def statements from log of IDLE command prompt.

C:\py>script_from_examples.py ex2.txt
def sum(a,b):
# Expected:
##         return a+b


C:\py>type ex2.txt
>>> def sum(a,b):
        return a+b


Plain CMD Python prompt shows it differently:

>>> def sum(a,b):
...     return a+b
...
pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: