Executes code blocks for a python shell.

    Parses the code in `elem.text` into blocks and
    executes them.

    Args:
        elem The AST element.
        doc  The document.

    Return:
        The code with inline results.

def execute_interactive_code(elem, doc):
    """Executes code blocks for a python shell.

    Parses the code in `elem.text` into blocks and
    executes them.

    Args:
        elem The AST element.
        doc  The document.

    Return:
        The code with inline results.
    """
    code_lines = [l[4:] for l in elem.text.split('\n')]

    code_blocks = [[code_lines[0]]]
    for line in code_lines[1:]:
        if line.startswith(' ') or line == '':
            code_blocks[-1].append(line)
        else:
            code_blocks.append([line])

    final_code = []
    try:
        child = replwrap.REPLWrapper("python", ">>> ", None)
    except NameError:
        pf.debug('Can not run interactive session. No output produced ' +
                 '(Code was:\n{!s}\n)'
                 .format(elem))
        pf.debug('Please pip install pexpect.')
        return ''
    for code_block in code_blocks:
        result = child.run_command('\n'.join(code_block) + '\n').rstrip('\r\n')
        final_code += [('>>> ' if i == 0 else '... ') + l for i, l in
                       enumerate(code_block)]
        if result:
            final_code += [r for r in result.split('\n')
                           if r.strip() not in code_block]
    return '\n'.join(final_code)