Skip to content

Instantly share code, notes, and snippets.

@mwaskom
Last active July 25, 2019 14:56
Show Gist options
  • Save mwaskom/00c8d9dfc21591a0de16dad7a8737c3b to your computer and use it in GitHub Desktop.
Save mwaskom/00c8d9dfc21591a0de16dad7a8737c3b to your computer and use it in GitHub Desktop.
IPython magic to automate injecting import statements into a terminal/notebook. Put in ~/.ipython/profile_default/startup and call %imports <os> <fmri>
from IPython.core.magic import Magics, magics_class, line_magic
@magics_class
class Imports(Magics):
@line_magic
def imports(self, opts):
lines = []
if "os" in opts:
lines.extend([
"import os",
"import os.path as op",
])
lines.extend([
"import numpy as np",
"import pandas as pd",
"import seaborn as sns",
"import matplotlib.pyplot as plt",
])
if "fmri" in opts:
lines.extend([
"import nibabel as nib",
"import lyman",
])
self.shell.set_next_input("\n".join(lines), replace=True)
ip = get_ipython()
ip.register_magics(Imports)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment