3

I have a simple python script (say, simple.py) , like

a = 5
b = a + a
print(b)

But I want the following: output the result as if these commands were executed in the interpreter, like

>>> a = 5
>>> b = a + a
>>> print(b)
10

And I want this in stdout :) Is that possible in some simple way? Also the same question for IPython. This question can be helpful for writing a small "how-to" for working with Python/IPython interpreters

4 Answers 4

3

You can use the exec statement to execute a line of code (the following is Python 2 code, change the print statements to print() if you want it to be Python 3):

import sys

def run(filename):
    with open(filename) as f:
        for line in f:
            print ">>> ", line
            exec line

if __name__ == "__main__":
    try:
        run(sys.argv[1])
    except KeyError:
        print "You should pass one filename as parameter."

I should note that it does not appear to handle multi-line statements very well yet (as it's evaluating each line separately).

Sign up to request clarification or add additional context in comments.

2 Comments

Trivial modification: output is double spaced, add a trailing comma to the print
@cdarke: I mean during execution. For example, the statement for i in xrange(10): print x won't work because it's evaluating for i in xrange(10): separately.
2

I modified from @Simeon 's code.

Save the code below as theprinter.py

import sys
if __name__ == '__main__':
    c = {}
    for line in sys.stdin:
        sys.stdout.write('>>> %s' % line)
        exec(line, c)

Usage: cat yourscript.py | python theprinter.py

Comments

1

Depending on which tools you are using to create your how-to, you may also want to use Sphinx, which is a tool to produce documentation in Python. It is able to output many formats, notably HTML and PDF. It has a very nice doctest module which allows to put Python instructions in your documentation. They will be run when you compile your documentation and the instructions as well as their results will be displayed.

2 Comments

No, Sphinx is really nice to make Python documentation/how-tos. This is not exactly what the poster asked, but it is an option to consider when making Python documentation.
Thank you! Actually I am using Emacs org-mode (+org-babel) for mixed Latex with executable code snipplets, maybe Sphinx can be incorporated this way, did not think about it yet.
0

This should be a good start for embedding and using a Python shell interactively (ActiveState code recipe).

For IPython, you could probably use IPShellEmbed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.