def script_from_examples(s):
 output = []
 for piece in DocTestParser().parse(s):
  if isinstance(piece, Example):
   output.append(piece.source[:(-1)])
   want = piece.want
   if want:
    output.append('# Expected:')
    output += [('## ' + l) for l in want.split('\n')[:(-1)]]
  else:
   output += [_comment_line(l) for l in piece.split('\n')[:(-1)]]
 while (output and (output[(-1)] == '#')):
  output.pop()
 while (output and (output[0] == '#')):
  output.pop(0)
 return ('\n'.join(output) + '\n')

def script_from_examples ( s ) : output = [ ] for piece in DocTestParser ( ) . parse ( s ) : if isinstance ( piece , Example ) : output . append ( piece . source [ : ( - 1 ) ] ) want = piece . want if want : output . append ( '# Expected:' ) output += [ ( '## ' + l ) for l in want . split ( '\n' ) [ : ( - 1 ) ] ] else : output += [ _comment_line ( l ) for l in piece . split ( '\n' ) [ : ( - 1 ) ] ] while ( output and ( output [ ( - 1 ) ] == '#' ) ) : output . pop ( ) while ( output and ( output [ 0 ] == '#' ) ) : output . pop ( 0 ) return ( '\n' . join ( output ) + '\n' )
extract script from text with examples .