Phil Lord
Phil Lord

Reputation: 3057

How to read next logical line in python

I would like to read the next logical line from a file into python, where logical means "according to the syntax of python".

I have written a small command which reads a set of statements from a file, and then prints out what you would get if you typed the statements into a python shell, complete with prompts and return values. Simple enough -- read each line, then eval. Which works just fine, until you hit a multi-line string.

I'm trying to avoid doing my own lexical analysis.

As a simple example, say I have a file containing

2 + 2

I want to print

>>> 2 + 2
4

and if I have a file with

"""Hello
World"""

I want to print

>>>> """Hello
...World"""
'Hello\nWorld'

The first of these is trivial -- read a line, eval, print. But then I need special support for comment lines. And now triple quotes. And so on.

Upvotes: 0

Views: 212

Answers (2)

Phil Lord
Phil Lord

Reputation: 3057

Okay, so resi had the correct idea. Here is my trivial code which does the job.

#!/usr/bin/python

import sys
import code

class Shell(code.InteractiveConsole):
    def write(data):
        print(data)

cons = Shell()

file_contents = sys.stdin

prompt = ">>> " 

for line in file_contents:
    print prompt + line,
    if cons.push(line.strip()):
        prompt = "... "
    else:
        prompt = ">>> "

Upvotes: 0

resi
resi

Reputation: 1788

You may want to take a look at the InteractiveInterpreter class from the code module .

The runsource() method shows how to deal with incomplete input.

Upvotes: 1

Related Questions