Created
April 14, 2021 14:32
-
-
Save Tantalus13A98B5F/5197bf0000297fd9a2df34c8709115be to your computer and use it in GitHub Desktop.
IPython magic for save & run a cell (optionally in a subprocess)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from IPython.core.magic import register_cell_magic | |
import subprocess | |
import argparse | |
import sys | |
import os | |
@register_cell_magic | |
def withsave(line, cell): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('fname') | |
parser.add_argument('-f', '--force', action='store_true') | |
parser.add_argument('-a', '--append', action='store_true') | |
parser.add_argument('--subp') | |
parser.add_argument('--no-capout', action='store_false', dest='capout') | |
args = parser.parse_args(line.split()) | |
if not args.fname.endswith('.py'): | |
args.fname += '.py' | |
assert not (args.force and args.append) | |
if os.path.exists(args.fname) and not (args.force or args.append): | |
raise FileExistsError(args.fname) | |
with open(args.fname, 'a' if args.append else 'w') as f: | |
f.write(cell) | |
if not args.subp: | |
get_ipython().run_cell(cell) | |
else: | |
get_ipython().user_ns[args.subp] = subprocess.run( | |
[sys.executable, args.fname], | |
capture_output=args.capout | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment