%%capture
# Your code here
print("This output will be captured and not displayed.")
2. Assigning Output to a Variable
By assigning the output to a variable, it won't automatically display in the notebook.
output = !echo "This output will be assigned to a variable."
3. Using Functions that Suppress Output
Some functions, by their nature, do not display output if they are not the last line in a cell, or they're explicitly returning values that can be suppressed.
import io
import contextlib
# Suppress print statements
f = io.StringIO()
with contextlib.redirect_stdout(f):
print("This will not be printed in the notebook.")
4. Hiding Output Using HTML and JavaScript
You can use HTML and JavaScript to create a collapsible cell output.
from IPython.display import display, HTML
display(HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle code cells on/off."></form>'''))
This will add a button that hides and shows the code cells when clicked.
5. Using I/O Redirection
You can redirect the output to /dev/null to effectively discard it.
import sys
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open('/dev/null', 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
with HiddenPrints():
print("This output will not be shown.")
6. Using contextlib to Redirect Output
Python's contextlib module can be used to redirect the output to nowhere:
import contextlib
with contextlib.redirect_stdout(None):
print("This will not be shown.")
Choose the method that best fits your specific needs and coding style.