Question: I'm trying to remove a layout with the click of a button.

I have this method in my MainActivity.java file:

```
public void goBack(View view) {
    TableLayout parent = (TableLayout) findViewById(R.id.activity_main);
    RelativeLayout child = (RelativeLayout) findViewById(R.id.activity_displayMessage);
    parent.removeView(child);
}

```

It is fired when this button is clicked in the view I want to remove:

```
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_removeView"
    android:onClick="goBack" />

```

But it gives me this message:

> 
> java.lang.IllegalStateException: Could not find method goBack(View) in
>  a parent or ancestor Context for android:onClick
> 
> 
> 

But MainActivity is my main file for all my methods, so I'm not sure why it can't find it.

Where should I put it so that it can be found?

Thanks!

Answer: 
You can do this by rebinding `sys.stdout`:

```
>>> def foo():
...     print('potato')
... 
>>> import sys, io
>>> sys.stdout = io.StringIO()
>>> foo()
>>> val = sys.stdout.getvalue()
>>> sys.stdout = sys.__stdout__  # restores original stdout
>>> print(val)
potato

```

For a nicer way to do it, consider writing a context manager. If you're on Python 3.4+, it's [already been written for you](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout).

```
>>> from contextlib import redirect_stdout
>>> f = io.StringIO()
>>> with redirect_stdout(f):
...     foo()
... 
>>> print(f.getvalue())
potato

```

In the case that you are able to modify the function itself, it may be cleaner to allow a dependency injection of the output stream (this is just a fancy way of saying "passing arguments"):

```
def foo(file=sys.stdout):
    print('potato', file=file)

```
The sensible solution is simple and obvious: fix the function so that it returns the correct data instead of printing it. Else you *can* use the hack posted by wim but assuming you have the hand on the faulty function resorting to such a convoluted solution falls into the "WTF" category. 

NB of course if you don't have the hand on the function's code or it's just for a 5 minutes one-shot script, capturing `sys.stdout` is a handy fallback.