Given the following input file:
a = 2
b = 3
c = a * b
d = c + 4
I want to run the above input file through a python program that produces the following output:
a = 2
b = 3
c = a * b = 6
d = c + 4 = 10
The input file is a legal python program, but the output is python with extra output that prints the value of each variable to the right of the declaration/assignment. Alternatively, the output could look like:
a = 2
b = 3
c = a * b
c = 6
d = c + 4
d = 10
The motivation for this is to implement a simple "engineer's notebook" that allows chains of calculations without needing print statements in the source file.
Here's what I have after modifying D.Shawley's (much appreciated) contribution:
#! /usr/bin/env python
from math import *
import sys
locals = dict()
for line in sys.stdin:
line = line.strip()
if line == '':
continue
saved = locals.copy()
stmt = compile(line,'<stdin>','single')
eval(stmt,None,locals)
print line,
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print