Skip to content

Instantly share code, notes, and snippets.

@switowski
Created July 15, 2020 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save switowski/301320fb6388822a76644461219e4386 to your computer and use it in GitHub Desktop.
Save switowski/301320fb6388822a76644461219e4386 to your computer and use it in GitHub Desktop.
import os
import sys
from contextlib import contextmanager
from copy import deepcopy
@contextmanager
def no_output():
original_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
yield
sys.stdout = original_stdout
def copy_namespace(local_ns):
copy_ns = {}
for key, value in local_ns.items():
try:
copy_ns[key] = deepcopy(value)
except TypeError:
# TypeError is raised when an object can't be pickled
copy_ns[key] = value
return copy_ns
def combine_multiline(lines):
new_lines = []
for line in lines:
if line.startswith(" ") and new_lines:
new_lines[-1] += line
else:
new_lines.append(line)
return new_lines
def curry_clean(ipython):
def clean_input(lines):
new_lines = []
lines = combine_multiline(lines)
local_ns = copy_namespace(ipython.user_ns)
for line in lines:
with no_output():
try:
exec(line, None, local_ns)
new_lines.append(line)
except Exception:
pass
return new_lines
return clean_input
def load_ipython_extension(ipython):
ipython.input_transformers_post.append(curry_clean(ipython))
def unload_ipython_extension(ipython):
ipython.input_transformers_post = [
f for f in ipython.input_transformers_post if f.__name__ != "clean_input"
]
from IPython.core.magic import register_line_magic
@register_line_magic
def rerunplus(line):
get_ipython().run_line_magic("load_ext", "ignore_exceptions")
get_ipython().run_line_magic("rerun", line)
get_ipython().run_line_magic("unload_ext", "ignore_exceptions")
def load_ipython_extension(ipython):
ipython.register_magics(rerunplus)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment