Skip to content

Instantly share code, notes, and snippets.

@BrianChevalier
Last active February 25, 2020 05:52
Show Gist options
  • Save BrianChevalier/295c751efc88cf73d7aca2191092339b to your computer and use it in GitHub Desktop.
Save BrianChevalier/295c751efc88cf73d7aca2191092339b to your computer and use it in GitHub Desktop.
"""
A super simple Jupyter cell magic that writes the cell to `main.cpp` or
specified file, compiles the file using g++ and executes the code using
`./a.out`
Limitations: the cell must be a complete C++ program.
"""
from IPython.core.magic import (register_line_magic,
register_cell_magic)
import subprocess
from IPython.display import display, HTML
def output(message, type='plain'):
"""
Used to format cell output nicely.
"""
types = {
'plain': 'blue',
'error': 'red'
}
text = "<code>" + message + "</code>"
display(HTML(text))
def bash(command, type):
"""
Run bash script using subprocess
"""
out = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
if out.returncode != 0:
output(f'{type} Failed.')
output('-------------------\n')
output(stdout.decode("utf-8"), type='error')
return 'error'
else:
output(f'{type} successful!')
output('-------------------\n')
@register_cell_magic
def cpp(line, cell):
# default filename
if line == '':
filename = 'main.cpp'
else:
filename = line
# write disk to file
with open(filename, "w") as text_file:
text_file.write(cell)
out = bash(['g++', f'{filename}'], 'Compile')
if out != 'error':
bash(['./a.out'], 'Execution')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment