tags:

views:

151

answers:

1

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
A: 

Something like the following is a good start. It's not very Pythonic, but it is pretty close. It doesn't distinguish between newly added variables and modified ones.

#! /usr/bin/env python
import sys
locals = dict()
for line in sys.stdin:
    saved = locals.copy()
    stmt = compile(line, '<stdin>', 'single')
    eval(stmt, None, locals)
    print line.strip(),
    for (k,v) in locals.iteritems():
        if k not in saved:
            print '=', v,
    print
D.Shawley
That certainly evaluates each expression line-by-line but does not meet (either of) the output requirements in the question ;-) That said, it should give @gregben enough Python to be able to complete his assignment.
Johnsyweb
This is very, very helpful. Thank you!
gregben
I modified your code to skip blank lines. BTW, this is not an assignment. I was just looking for a simple replacement for mathcad that I could run in a terminal.
gregben
If you are looking for a quick calculator, you might want to try either [`bc`](http://www.opengroup.org/onlinepubs/009695399/utilities/bc.html) or [`dc`](http://www.FreeBSD.org/cgi/man.cgi?query=dc). I end up using `dc` more than I would like to admit for those quick little calculations.
D.Shawley
I've used bc and dc from before I can remember. Trying to create an extensive set of calcs with documentation. Trying 'smath studio' right now. Thanks again.
gregben