Last active
February 25, 2020 05:52
-
-
Save BrianChevalier/295c751efc88cf73d7aca2191092339b to your computer and use it in GitHub Desktop.
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
""" | |
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