Skip to content

Commit

Permalink
Fix #1.
Browse files Browse the repository at this point in the history
Move tests directory to make VSCode 'Discover Tests' feature work
  • Loading branch information
breathe committed Nov 21, 2018
1 parent 575a0aa commit 2686bf9
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 22 deletions.
4 changes: 2 additions & 2 deletions Example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -27,7 +27,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
Expand Down
70 changes: 66 additions & 4 deletions NotebookScripter/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,83 @@

from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.core.magic import Magics, magics_class, line_magic

from traitlets import Bool, CBool, Unicode
from traitlets.config import MultipleInstanceError

from nbformat import read


class NotebookScripterEmbeddedIpythonShell(InteractiveShell):

def init_sys_modules(self):
"""Override this to create an ipython shell appropriate for embedding similar to InteractiveShellEmbed.
Needed to avoid creating new global namespace when running from command line console.
"""
pass

def init_prompts(self):
"""Override: don't mutate shell prompts. Needed to avoid overtaking the interactive shell when this code is run from `python` command line console."""
# Set system prompts, so that scripts can decide if they are running
# interactively.
# sys.ps1 = 'In : '
# sys.ps2 = '...: '
# sys.ps3 = 'Out: '


def register_magic(shell_instance, magic_cls):
"""
Registers the provided shell_instance from IPython.
Returns a function which undoes this.
Rant: Why the f... does IPython not define it's own unregister function?
:param magic_cls: The Magics class you wish to register.
"""

# ugh I hate this code and I hate python so much ...
undoes = {}
original_magics = shell_instance.magics_manager.magics
for magic_type, names in magic_cls.magics.items():
if magic_type in original_magics:
for magic_name, _ in names.items():
if magic_name in original_magics[magic_type]:
undoesNamedMagics = undoes.setdefault(magic_type, {})
undoesNamedMagics[magic_name] = original_magics[magic_type][magic_name]

shell_instance.register_magics(magic_cls)

def unregister_magics():
for magic_type, magic_names in undoes.items():
for magic_name, magic_value in magic_names.items():
shell_instance.magics_manager.magics[magic_type][magic_name] = magic_value

return unregister_magics


def run_notebook(
path_to_notebook: str,
initial_values_for_ns: typing.Dict = None,
with_backend='agg'
) -> typing.Any:
"""Run a notebook as a module within this processes namespace"""

shell = InteractiveShell.instance()
try:
shell = NotebookScripterEmbeddedIpythonShell.instance()
except MultipleInstanceError:
# we are already embedded into an ipython shell -- just get that one.
shell = get_ipython()

unregister_magics = None

if with_backend:
try:
# try to initialize the matplotlib backend as early as possible
# (cuts down on potential for complex bugs)
# try to initialize the matplotlib backend as early as possible
# (cuts down on potential for complex bugs)
import matplotlib
matplotlib.use(with_backend, force=True)
except ModuleNotFoundError:
Expand All @@ -39,7 +98,7 @@ def matplotlib(self, _line):
import matplotlib
matplotlib.use(with_backend, force=True)

shell.register_magics(NotebookScripterMagics)
unregister_magics = register_magic(shell, NotebookScripterMagics)

# load the notebook object
with io.open(path_to_notebook, 'r', encoding='utf-8') as f:
Expand Down Expand Up @@ -77,6 +136,9 @@ def matplotlib(self, _line):
raise err
finally:
shell.user_ns = save_user_ns
# revert the magics changes ...
if unregister_magics:
unregister_magics()
return dynamic_module


Expand Down
14 changes: 0 additions & 14 deletions NotebookScripter/tests/snapshots/snap_TestNotebookScripter.py

This file was deleted.

2 changes: 1 addition & 1 deletion requirements_test.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
-r requirements.txt
-r requirements_test_runner.txt
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='NotebookScripter',
version='1.0.4',
version='1.0.5',
packages=('NotebookScripter',),
url='https://github.com/breathe/NotebookScripter',
license='MIT',
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ def setUp(self):

def test_run_notebook(self):
notebook_file = os.path.join(os.path.dirname(__file__), "./Test.ipynb")
globals()
mod = NotebookScripter.run_notebook(notebook_file, with_backend='agg')
value = mod.hello()
print(value)
Expand Down
File renamed without changes.
File renamed without changes.

0 comments on commit 2686bf9

Please sign in to comment.