How do I perform some operation on the output of a function in Python?
Question: I am trying to make a function's output behave as if it's my input. The goal
is to make a new output from the old output.

I have some code that looks like this:

    
    
    def func():
    
        BLOCK OF CODE
    
    func()
    

There is no return statement in the function and no parameters within the
parenthesis. When I type `func()` to call my function as shown above, I get
the desired output, which is a bunch of printed statements. Now I want to do
something with that output to get another output. All I'm trying to do is
effectively "pipe" the output of one function into the input of another
function (or, if possible, not even worry about creating another function at
all, and instead doing something more direct). I looked into [Python 3 writing
to a pipe](http://stackoverflow.com/questions/5965874/python-3-writing-to-a-
pipe) but it did not help me. I also tried defining another function and using
the preceding function as a parameter, which did not work either:

    
    
    def another_func(func):
        print another_statement
    
    another_func(func)
    

I also tried making a closure (which "kind" of worked because at least it
printed the same thing that func() would print, but still not very
encouraging):

    
    
    def func():
        def another_func():
            print another_statement
        BLOCK OF CODE
    
    another_func()
    

Finally, I tried designing both a decorator and a nested function to
accomplish this, but I have no parameters in my function, which really threw
off my code (didn't print anything at all).

Any advice on how to manipulate a function's output like as if it is your
input so that it's possible to create a new output?


Answer: You _could_ achieve this by redirecting stdout using a decorator:

    
    
    from StringIO import StringIO
    import sys
    
    def pipe(f):
        def decorated(*args, **kwargs):
            old,sys.stdout = sys.stdout,StringIO()
    
            try:
                result = f(*args, **kwargs)
                output = sys.stdout.getvalue()
            finally:
                sys.stdout = old
    
            return result, output
        return decorated
    

You could then get the `result, output` pair from any decorated function, eg:

    
    
    @pipe
    def test(x):
        print x
        return 0
    
    test(3) -> (0, '3\n')
    

* * *

However, I can't think of a good reason why you'd _want_ to do this.

(Actually, that's not _quite_ true; it is handy when writing unit tests for
user IO, such as when testing student assignments in a software engineering
course. I seriously doubt that that's what the OP is trying to do, though.)

