def setUp(self):
        self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)]))
        """Temporary  (probably) valid python package name."""

        self.value = int(random.random() * 10000)

        self.tempdir = TemporaryDirectory()
        self.__orig_cwd = os.getcwd()
        sys.path.insert(0, self.tempdir.name)

        self.writefile(os.path.join(package, '__init__.py'), '')
        self.writefile(os.path.join(package, 'sub.py'), """
        x = {0!r}
        """.format(self.value))
        self.writefile(os.path.join(package, 'relative.py'), """
        from .sub import x
        """)
        self.writefile(os.path.join(package, 'absolute.py'), """
        from {0}.sub import x
        """.format(package))
        self.writefile(os.path.join(package, 'args.py'), """
        import sys
        a = " ".join(sys.argv[1:])
        """.format(package))
예제 #2
0
def install_sos_kernel_spec(args):
    user = False
    prefix = None
    if args.sys_prefix:
        prefix = sys.prefix
    elif args.prefix:
        prefix = args.prefix
    elif args.user or not _is_root():
        user = True

    with TemporaryDirectory() as td:
        os.chmod(td, 0o755)  # Starts off as 700, not user readable
        with open(os.path.join(td, 'kernel.json'), 'w') as f:
            json.dump(kernel_json, f, sort_keys=True)
        # Copy resources once they're specified
        shutil.copy(os.path.join(os.path.split(__file__)[
                    0], 'kernel.js'), os.path.join(td, 'kernel.js'))
        shutil.copy(os.path.join(os.path.split(__file__)[
                    0], 'logo-64x64.png'), os.path.join(td, 'logo-64x64.png'))

        KS = KernelSpecManager()
        KS.log.setLevel(logging.ERROR)
        KS.install_kernel_spec(td, 'sos', user=user, replace=True, prefix=prefix)
        print('sos jupyter kernel spec is installed')
예제 #3
0
def test_local_file_completions():
    ip = get_ipython()
    cwd = py3compat.getcwd()
    try:
        with TemporaryDirectory() as tmpdir:
            os.chdir(tmpdir)
            prefix = './foo'
            suffixes = ['1', '2']
            names = [prefix + s for s in suffixes]
            for n in names:
                open(n, 'w').close()

            # Check simple completion
            c = ip.complete(prefix)[1]
            nt.assert_equal(c, names)

            # Now check with a function call
            cmd = 'a = f("%s' % prefix
            c = ip.complete(prefix, cmd)[1]
            comp = [prefix + s for s in suffixes]
            nt.assert_equal(c, comp)
    finally:
        # prevent failures from making chdir stick
        os.chdir(cwd)
예제 #4
0
    def test_save_notebook(self):
        with TemporaryDirectory() as td:
            # Test in the root directory
            # Create a notebook
            nm = FileNotebookManager(notebook_dir=td)
            model = nm.create_notebook()
            name = model['name']
            path = model['path']

            # Get the model with 'content'
            full_model = nm.get_notebook(name, path)

            # Save the notebook
            model = nm.save_notebook(full_model, name, path)
            assert isinstance(model, dict)
            self.assertIn('name', model)
            self.assertIn('path', model)
            self.assertEqual(model['name'], name)
            self.assertEqual(model['path'], path)

            # Test in sub-directory
            # Create a directory and notebook in that directory
            sub_dir = '/foo/'
            self.make_dir(nm.notebook_dir, 'foo')
            model = nm.create_notebook(None, sub_dir)
            name = model['name']
            path = model['path']
            model = nm.get_notebook(name, path)

            # Change the name in the model for rename
            model = nm.save_notebook(model, name, path)
            assert isinstance(model, dict)
            self.assertIn('name', model)
            self.assertIn('path', model)
            self.assertEqual(model['name'], 'Untitled0.ipynb')
            self.assertEqual(model['path'], sub_dir.strip('/'))
예제 #5
0
def main():
    args = parse_args()
    kernel_env = make_kernel_env(args)
    validate_kernel_env(kernel_env)

    script_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    kernel_json = {
        'argv': [
            sys.executable,
            os.path.join(script_dir, 'parent_kernel.py'),
            '-f',
            '{connection_file}',
        ],
        'display_name':
        args.kernel_name,
        'language':
        'swift',
        'env':
        kernel_env,
    }

    print('kernel.json:\n%s\n' % json.dumps(kernel_json, indent=2))

    kernel_code_name = get_kernel_code_name(args.kernel_name)

    with TemporaryDirectory() as td:
        os.chmod(td, 0o755)
        with open(os.path.join(td, 'kernel.json'), 'w') as f:
            json.dump(kernel_json, f, indent=2)
        KernelSpecManager().install_kernel_spec(td,
                                                kernel_code_name,
                                                user=args.user,
                                                prefix=args.prefix)

    print('Registered kernel \'{}\' as \'{}\'!'.format(args.kernel_name,
                                                       kernel_code_name))
예제 #6
0
 def start(self):
     kernel_spec = self.kernel_class().kernel_json
     with TemporaryDirectory() as td:
         dirname = os.path.join(td, kernel_spec['name'])
         os.mkdir(dirname)
         with open(os.path.join(dirname, 'kernel.json'), 'w') as f:
             json.dump(kernel_spec, f, sort_keys=True)
         filenames = ['logo-64x64.png', 'logo-32x32.png']
         name = self.kernel_class.__module__
         for filename in filenames:
             try:
                 data = pkgutil.get_data(name.split('.')[0],
                                         'images/' + filename)
             except (OSError, IOError):
                 data = pkgutil.get_data('metakernel',
                     'images/' + filename)
             with open(os.path.join(dirname, filename), 'wb') as f:
                 f.write(data)
         try:
             subprocess.check_call(
                 [sys.executable, '-m', 'jupyter',
                 'kernelspec', 'install'] + self.argv + [dirname])
         except CalledProcessError as exc:
             sys.exit(exc.returncode)
예제 #7
0
    def test_regScoreAssess2(self):
        stat = self.sas.sasstat()
        self.sas.submit("""
        data work.class;
            set sashelp.class;
        run;
        """)
        tr = self.sas.sasdata("class", "work")
        tr.set_results('PANDAS')
        with TemporaryDirectory() as temppath:
            fname = os.path.join(temppath, 'hplogistic_code.sas')
            b = stat.hplogistic(data=tr, cls= 'sex', model='sex = weight height', code=fname)
            # This also works with hardcoded strings
            # b = stat.hplogistic(data=tr, cls='sex', model='sex = weight height', code=r'c:\public\foo.sas')
            tr.score(file=fname)
            # check that P_SexF is in columnInfo
            self.assertTrue('P_SexF' in tr.columnInfo()['Variable'].values, msg="Prediction Column not found")

        res1 = tr.assessModel(target='sex', prediction='P_SexF', nominal=True, event='F')
        a = ['ASSESSMENTBINSTATISTICS', 'ASSESSMENTSTATISTICS', 'LOG', 'SGPLOT']
        self.assertEqual(sorted(a), sorted(res1.__dir__()),
                         msg=u" model failed to return correct objects expected:{0:s}  returned:{1:s}".format(
                             str(a), str(b)))
        self.assertIsInstance(res1, SASresults, "Is return type correct")
예제 #8
0
def test_atomic_writing_newlines():
    with TemporaryDirectory() as td:
        path = os.path.join(td, 'testfile')

        lf = u'a\nb\nc\n'
        plat = lf.replace(u'\n', os.linesep)
        crlf = lf.replace(u'\n', u'\r\n')

        # test default
        with stdlib_io.open(path, 'w') as f:
            f.write(lf)
        with stdlib_io.open(path, 'r', newline='') as f:
            read = f.read()
        nt.assert_equal(read, plat)

        # test newline=LF
        with stdlib_io.open(path, 'w', newline='\n') as f:
            f.write(lf)
        with stdlib_io.open(path, 'r', newline='') as f:
            read = f.read()
        nt.assert_equal(read, lf)

        # test newline=CRLF
        with atomic_writing(path, newline='\r\n') as f:
            f.write(lf)
        with stdlib_io.open(path, 'r', newline='') as f:
            read = f.read()
        nt.assert_equal(read, crlf)

        # test newline=no convert
        text = u'crlf\r\ncr\rlf\n'
        with atomic_writing(path, newline='') as f:
            f.write(text)
        with stdlib_io.open(path, 'r', newline='') as f:
            read = f.read()
        nt.assert_equal(read, text)
예제 #9
0
    def test_escape_root(self):
        with TemporaryDirectory() as td:
            cm = FileContentsManager(root_dir=td)
            # make foo, bar next to root
            with open(os.path.join(cm.root_dir, '..', 'foo'), 'w') as f:
                f.write('foo')
            with open(os.path.join(cm.root_dir, '..', 'bar'), 'w') as f:
                f.write('bar')

            with self.assertRaisesHTTPError(404):
                cm.get('..')
            with self.assertRaisesHTTPError(404):
                cm.get('foo/../../../bar')
            with self.assertRaisesHTTPError(404):
                cm.delete('../foo')
            with self.assertRaisesHTTPError(404):
                cm.rename('../foo', '../bar')
            with self.assertRaisesHTTPError(404):
                cm.save(model={
                    'type': 'file',
                    'content': u'',
                    'format': 'text',
                },
                        path='../foo')
예제 #10
0
 def test_missing_root_dir(self):
     with TemporaryDirectory() as td:
         root = os.path.join(td, 'notebook', 'dir', 'is', 'missing')
         self.assertRaises(TraitError, FileContentsManager, root_dir=root)
 def test_missing_nb_dir(self):
     with TemporaryDirectory() as td:
         nbdir = os.path.join(td, 'notebook', 'dir', 'is', 'missing')
         self.assertRaises(TraitError,
                           FileNotebookManager,
                           notebook_dir=nbdir)
 def test_nb_dir(self):
     with TemporaryDirectory() as td:
         km = FileNotebookManager(notebook_dir=td)
         self.assertEqual(km.notebook_dir, td)
예제 #13
0
 def setUp(self):
     self.tempdir = TemporaryDirectory()
     self.src = self.dst("src")
     with open(self.src, "w") as f:
         f.write("Hello, world!")
예제 #14
0
 def tempdir(self):
     td = TemporaryDirectory()
     self.tempdirs.append(td)
     return py3compat.cast_unicode(td.name)
예제 #15
0
파일: install.py 프로젝트: KenyC/I2dris
kernel_json = {
    "argv": [
        "python",
        os.path.join(os.getcwd(), "kernel.py"), "-f", "{connection_file}"
    ],
    "display_name":
    "Idris",
    "language":
    "idris",
    "name":
    "i2dris",
    "code_mirror_mode":
    "haskell"
}

try:
    from jupyter_client.kernelspec import install_kernel_spec
except ImportError:
    from IPython.kernel.kernelspec import install_kernel_spec

from IPython.utils.tempdir import TemporaryDirectory

with TemporaryDirectory() as temp_directory:
    os.chmod(temp_directory, 0o755)  # Starts off as 700, not user readable

    with open(os.path.join(temp_directory, 'kernel.json'), 'w') as f:
        json.dump(kernel_json, f, sort_keys=True)

    kernel_name = kernel_json['name']

    install_kernel_spec(temp_directory, kernel_name, user=True, replace=True)
예제 #16
0
def test_history():
    ip = get_ipython()
    with TemporaryDirectory() as tmpdir:
        hist_manager_ori = ip.history_manager
        hist_file = os.path.join(tmpdir, "history.sqlite")
        try:
            ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
            hist = [u"a=1", u"def f():\n    test = 1\n    return test", u"b='€Æ¾÷ß'"]
            for i, h in enumerate(hist, start=1):
                ip.history_manager.store_inputs(i, h)

            ip.history_manager.db_log_output = True
            # Doesn't match the input, but we'll just check it's stored.
            ip.history_manager.output_hist_reprs[3] = "spam"
            ip.history_manager.store_output(3)

            nt.assert_equal(ip.history_manager.input_hist_raw, [""] + hist)

            # Detailed tests for _get_range_session
            grs = ip.history_manager._get_range_session
            nt.assert_equal(
                list(grs(start=2, stop=-1)), list(zip([0], [2], hist[1:-1]))
            )
            nt.assert_equal(list(grs(start=-2)), list(zip([0, 0], [2, 3], hist[-2:])))
            nt.assert_equal(
                list(grs(output=True)),
                list(zip([0, 0, 0], [1, 2, 3], zip(hist, [None, None, "spam"]))),
            )

            # Check whether specifying a range beyond the end of the current
            # session results in an error (gh-804)
            ip.magic("%hist 2-500")

            # Check that we can write non-ascii characters to a file
            ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1"))
            ip.magic("%%hist -pf %s" % os.path.join(tmpdir, "test2"))
            ip.magic("%%hist -nf %s" % os.path.join(tmpdir, "test3"))
            ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test4"))

            # New session
            ip.history_manager.reset()
            newcmds = [u"z=5", u"class X(object):\n    pass", u"k='p'", u"z=5"]
            for i, cmd in enumerate(newcmds, start=1):
                ip.history_manager.store_inputs(i, cmd)
            gothist = ip.history_manager.get_range(start=1, stop=4)
            nt.assert_equal(list(gothist), list(zip([0, 0, 0], [1, 2, 3], newcmds)))
            # Previous session:
            gothist = ip.history_manager.get_range(-1, 1, 4)
            nt.assert_equal(list(gothist), list(zip([1, 1, 1], [1, 2, 3], hist)))

            newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]

            # Check get_hist_tail
            gothist = ip.history_manager.get_tail(5, output=True, include_latest=True)
            expected = [(1, 3, (hist[-1], "spam"))] + [
                (s, n, (c, None)) for (s, n, c) in newhist
            ]
            nt.assert_equal(list(gothist), expected)

            gothist = ip.history_manager.get_tail(2)
            expected = newhist[-3:-1]
            nt.assert_equal(list(gothist), expected)

            # Check get_hist_search

            gothist = ip.history_manager.search("*test*")
            nt.assert_equal(list(gothist), [(1, 2, hist[1])])

            gothist = ip.history_manager.search("*=*")
            nt.assert_equal(
                list(gothist),
                [
                    (1, 1, hist[0]),
                    (1, 2, hist[1]),
                    (1, 3, hist[2]),
                    newhist[0],
                    newhist[2],
                    newhist[3],
                ],
            )

            gothist = ip.history_manager.search("*=*", n=4)
            nt.assert_equal(
                list(gothist), [(1, 3, hist[2]), newhist[0], newhist[2], newhist[3]]
            )

            gothist = ip.history_manager.search("*=*", unique=True)
            nt.assert_equal(
                list(gothist),
                [
                    (1, 1, hist[0]),
                    (1, 2, hist[1]),
                    (1, 3, hist[2]),
                    newhist[2],
                    newhist[3],
                ],
            )

            gothist = ip.history_manager.search("*=*", unique=True, n=3)
            nt.assert_equal(list(gothist), [(1, 3, hist[2]), newhist[2], newhist[3]])

            gothist = ip.history_manager.search("b*", output=True)
            nt.assert_equal(list(gothist), [(1, 3, (hist[2], "spam"))])

            # Cross testing: check that magic %save can get previous session.
            testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
            ip.magic("save " + testfilename + " ~1/1-3")
            with io.open(testfilename, encoding="utf-8") as testfile:
                nt.assert_equal(
                    testfile.read(), u"# coding: utf-8\n" + u"\n".join(hist) + u"\n"
                )

            # Duplicate line numbers - check that it doesn't crash, and
            # gets a new session
            ip.history_manager.store_inputs(1, "rogue")
            ip.history_manager.writeout_cache()
            nt.assert_equal(ip.history_manager.session_number, 3)
        finally:
            # Ensure saving thread is shut down before we try to clean up the files
            ip.history_manager.save_thread.stop()
            # Forcibly close database rather than relying on garbage collection
            ip.history_manager.db.close()
            # Restore history manager
            ip.history_manager = hist_manager_ori
예제 #17
0
 def setUp(self):
     self._temp_dir = TemporaryDirectory()
     self.td = self._temp_dir.name
     self._file_manager = FileContentsManager(root_dir=self.td)
     self.contents_manager = HybridContentsManager(
         managers={'': self._file_manager})
예제 #18
0
def install_nbextension(files,
                        overwrite=False,
                        symlink=False,
                        ipython_dir=None,
                        verbose=1):
    """Install a Javascript extension for the notebook
    
    Stages files and/or directories into IPYTHONDIR/nbextensions.
    By default, this compares modification time, and only stages files that need updating.
    If `overwrite` is specified, matching files are purged before proceeding.
    
    Parameters
    ----------
    
    files : list(paths or URLs)
        One or more paths or URLs to existing files directories to install.
        These will be installed with their base name, so '/path/to/foo'
        will install to 'nbextensions/foo'.
        Archives (zip or tarballs) will be extracted into the nbextensions directory.
    overwrite : bool [default: False]
        If True, always install the files, regardless of what may already be installed.
    symlink : bool [default: False]
        If True, create a symlink in nbextensions, rather than copying files.
        Not allowed with URLs or archives.
    ipython_dir : str [optional]
        The path to an IPython directory, if the default value is not desired.
        get_ipython_dir() is used by default.
    verbose : int [default: 1]
        Set verbosity level. The default is 1, where file actions are printed.
        set verbose=2 for more output, or verbose=0 for silence.
    """

    ipython_dir = ipython_dir or get_ipython_dir()
    nbext = pjoin(ipython_dir, u'nbextensions')
    # make sure nbextensions dir exists
    if not os.path.exists(nbext):
        os.makedirs(nbext)

    if isinstance(files, string_types):
        # one file given, turn it into a list
        files = [files]

    for path in map(cast_unicode_py2, files):

        if path.startswith(('https://', 'http://')):
            if symlink:
                raise ValueError("Cannot symlink from URLs")
            # Given a URL, download it
            with TemporaryDirectory() as td:
                filename = urlparse(path).path.split('/')[-1]
                local_path = os.path.join(td, filename)
                if verbose >= 1:
                    print("downloading %s to %s" % (path, local_path))
                urlretrieve(path, local_path)
                # now install from the local copy
                install_nbextension(local_path, overwrite, symlink,
                                    ipython_dir, verbose)
            continue

        # handle archives
        archive = None
        if path.endswith('.zip'):
            archive = zipfile.ZipFile(path)
        elif _safe_is_tarfile(path):
            archive = tarfile.open(path)

        if archive:
            if symlink:
                raise ValueError("Cannot symlink from archives")
            if verbose >= 1:
                print("extracting %s to %s" % (path, nbext))
            archive.extractall(nbext)
            archive.close()
            continue

        dest = pjoin(nbext, basename(path))
        if overwrite and os.path.exists(dest):
            if verbose >= 1:
                print("removing %s" % dest)
            if os.path.isdir(dest):
                shutil.rmtree(dest)
            else:
                os.remove(dest)

        if symlink:
            path = os.path.abspath(path)
            if not os.path.exists(dest):
                if verbose >= 1:
                    print("symlink %s -> %s" % (dest, path))
                os.symlink(path, dest)
            continue

        if os.path.isdir(path):
            strip_prefix_len = len(path) - len(basename(path))
            for parent, dirs, files in os.walk(path):
                dest_dir = pjoin(nbext, parent[strip_prefix_len:])
                if not os.path.exists(dest_dir):
                    if verbose >= 2:
                        print("making directory %s" % dest_dir)
                    os.makedirs(dest_dir)
                for file in files:
                    src = pjoin(parent, file)
                    # print("%r, %r" % (dest_dir, file))
                    dest = pjoin(dest_dir, file)
                    _maybe_copy(src, dest, verbose)
        else:
            src = path
            _maybe_copy(src, dest, verbose)
예제 #19
0
 def test_create_nbextensions(self):
     with TemporaryDirectory() as ipdir:
         install_nbextension(self.src, ipython_dir=ipdir)
         self.assert_installed(pjoin(basename(self.src), u'ƒile'), ipdir)
예제 #20
0
 def test_create_nbextensions_user(self):
     with TemporaryDirectory() as td:
         self.ipdir = ipdir = pjoin(td, u'ipython')
         install_nbextension(self.src, user=True)
         self.assert_installed(pjoin(basename(self.src), u'ƒile'),
                               user=True)
예제 #21
0
 def test_notebook_export_json(self):
     with TemporaryDirectory() as td:
         outfile = os.path.join(td, "nb.ipynb")
         _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
         _ip.magic("notebook -e %s" % outfile)
예제 #22
0
from distutils.command.install import installfrom distutils.core import setupfrom distutils import logimport osimport jsonimport sys
kernel_json = { "argv": [sys.executable, "-m", "calysto_processing", "-f", "{connection_file}"], "display_name": "Calysto Processing", "language": "java", "name": "calysto_processing", "env": {"PROCESSING_JAVA": "processing-java"}}
class install_with_kernelspec(install): def run(self):        install.run(self) from IPython.kernel.kernelspec import install_kernel_spec from IPython.utils.tempdir import TemporaryDirectory from metakernel.utils.kernel import install_kernel_resources with TemporaryDirectory() as td:            os.chmod(td, 0o755) # Starts off as 700, not user readable with open(os.path.join(td, 'kernel.json'), 'w') as f:                json.dump(kernel_json, f, sort_keys=True)            install_kernel_resources(td, resource="calysto_processing")            log.info('Installing kernel spec') try:                install_kernel_spec(td, 'calysto_processing', user=self.user, replace=True) except:                install_kernel_spec(td, 'calysto_processing', user=not self.user, replace=True)
svem_flag = '--single-version-externally-managed'if svem_flag in sys.argv: # Die, setuptools, die.    sys.argv.remove(svem_flag)
with open('calysto_processing/__init__.py', 'rb') as fid: for line in fid:        line = line.decode('utf-8') if line.startswith('__version__'): __version__ = line.strip().split()[-1][1:-1] break
with open('README.md') as f:    readme = f.read()
setup(name='calysto_processing', version=__version__, description='A ProcessingJS kernel for Jupyter', long_description=readme, url="https://github.com/Calysto/calysto_processing", author='Douglas Blank', author_email='*****@*****.**', install_requires=["metakernel", "html2text"], packages=["calysto_processing"], cmdclass={'install': install_with_kernelspec}, classifiers = [ 'Framework :: IPython', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 2', 'Topic :: System :: Shells',      ])
예제 #23
0
def test_history():
    ip = get_ipython()
    with TemporaryDirectory() as tmpdir:
        hist_manager_ori = ip.history_manager
        hist_file = os.path.join(tmpdir, 'history.sqlite')
        try:
            ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
            hist = [
                u'a=1', u'def f():\n    test = 1\n    return test',
                u"b='€Æ¾÷ß'"
            ]
            for i, h in enumerate(hist, start=1):
                ip.history_manager.store_inputs(i, h)

            ip.history_manager.db_log_output = True
            # Doesn't match the input, but we'll just check it's stored.
            ip.history_manager.output_hist_reprs[3] = "spam"
            ip.history_manager.store_output(3)

            nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)

            # Detailed tests for _get_range_session
            grs = ip.history_manager._get_range_session
            nt.assert_equal(list(grs(start=2, stop=-1)),
                            zip([0], [2], hist[1:-1]))
            nt.assert_equal(list(grs(start=-2)), zip([0, 0], [2, 3],
                                                     hist[-2:]))
            nt.assert_equal(
                list(grs(output=True)),
                zip([0, 0, 0], [1, 2, 3], zip(hist, [None, None, 'spam'])))

            # Check whether specifying a range beyond the end of the current
            # session results in an error (gh-804)
            ip.magic('%hist 2-500')

            # Check that we can write non-ascii characters to a file
            ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1"))
            ip.magic("%%hist -pf %s" % os.path.join(tmpdir, "test2"))
            ip.magic("%%hist -nf %s" % os.path.join(tmpdir, "test3"))
            ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test4"))

            # New session
            ip.history_manager.reset()
            newcmds = ["z=5", "class X(object):\n    pass", "k='p'"]
            for i, cmd in enumerate(newcmds, start=1):
                ip.history_manager.store_inputs(i, cmd)
            gothist = ip.history_manager.get_range(start=1, stop=4)
            nt.assert_equal(list(gothist), zip([0, 0, 0], [1, 2, 3], newcmds))
            # Previous session:
            gothist = ip.history_manager.get_range(-1, 1, 4)
            nt.assert_equal(list(gothist), zip([1, 1, 1], [1, 2, 3], hist))

            # Check get_hist_tail
            gothist = ip.history_manager.get_tail(4,
                                                  output=True,
                                                  include_latest=True)
            expected = [
                (1, 3, (hist[-1], "spam")),
                (2, 1, (newcmds[0], None)),
                (2, 2, (newcmds[1], None)),
                (2, 3, (newcmds[2], None)),
            ]
            nt.assert_equal(list(gothist), expected)

            gothist = ip.history_manager.get_tail(2)
            expected = [(2, 1, newcmds[0]), (2, 2, newcmds[1])]
            nt.assert_equal(list(gothist), expected)

            # Check get_hist_search
            gothist = ip.history_manager.search("*test*")
            nt.assert_equal(list(gothist), [(1, 2, hist[1])])
            gothist = ip.history_manager.search("b*", output=True)
            nt.assert_equal(list(gothist), [(1, 3, (hist[2], "spam"))])

            # Cross testing: check that magic %save can get previous session.
            testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
            ip.magic_save(testfilename + " ~1/1-3")
            with py3compat.open(testfilename) as testfile:
                nt.assert_equal(testfile.read(),
                                u"# coding: utf-8\n" + u"\n".join(hist))

            # Duplicate line numbers - check that it doesn't crash, and
            # gets a new session
            ip.history_manager.store_inputs(1, "rogue")
            ip.history_manager.writeout_cache()
            nt.assert_equal(ip.history_manager.session_number, 3)
        finally:
            # Restore history manager
            ip.history_manager = hist_manager_ori
예제 #24
0
 def setUp(self):
     self._temp_dir = TemporaryDirectory()
     self.td = self._temp_dir.name
     self.notebook_manager = FileNotebookManager(notebook_dir=self.td,
                                                 log=logging.getLogger())
 def test_create_nb_dir(self):
     with TemporaryDirectory() as td:
         nbdir = os.path.join(td, 'notebooks')
         km = FileNotebookManager(notebook_dir=nbdir)
         self.assertEqual(km.notebook_dir, nbdir)
예제 #26
0
def install_nbextension(files,
                        overwrite=False,
                        symlink=False,
                        user=False,
                        prefix=None,
                        nbextensions_dir=None,
                        verbose=1):
    """Install a Javascript extension for the notebook
    
    Stages files and/or directories into the nbextensions directory.
    By default, this compares modification time, and only stages files that need updating.
    If `overwrite` is specified, matching files are purged before proceeding.
    
    Parameters
    ----------
    
    files : list(paths or URLs)
        One or more paths or URLs to existing files directories to install.
        These will be installed with their base name, so '/path/to/foo'
        will install to 'nbextensions/foo'.
        Archives (zip or tarballs) will be extracted into the nbextensions directory.
    overwrite : bool [default: False]
        If True, always install the files, regardless of what may already be installed.
    symlink : bool [default: False]
        If True, create a symlink in nbextensions, rather than copying files.
        Not allowed with URLs or archives. Windows support for symlinks requires
        Vista or above, Python 3, and a permission bit which only admin users
        have by default, so don't rely on it.
    user : bool [default: False]
        Whether to install to the user's .ipython/nbextensions directory.
        Otherwise do a system-wide install (e.g. /usr/local/share/jupyter/nbextensions).
    prefix : str [optional]
        Specify install prefix, if it should differ from default (e.g. /usr/local).
        Will install to prefix/share/jupyter/nbextensions
    nbextensions_dir : str [optional]
        Specify absolute path of nbextensions directory explicitly.
    verbose : int [default: 1]
        Set verbosity level. The default is 1, where file actions are printed.
        set verbose=2 for more output, or verbose=0 for silence.
    """
    if sum(map(bool, [user, prefix, nbextensions_dir])) > 1:
        raise ArgumentConflict(
            "Cannot specify more than one of user, prefix, or nbextensions_dir."
        )
    if user:
        nbext = pjoin(get_ipython_dir(), u'nbextensions')
    else:
        if prefix:
            nbext = pjoin(prefix, 'share', 'jupyter', 'nbextensions')
        elif nbextensions_dir:
            nbext = nbextensions_dir
        else:
            nbext = SYSTEM_NBEXTENSIONS_INSTALL_DIR
    # make sure nbextensions dir exists
    ensure_dir_exists(nbext)

    if isinstance(files, string_types):
        # one file given, turn it into a list
        files = [files]

    for path in map(cast_unicode_py2, files):

        if path.startswith(('https://', 'http://')):
            if symlink:
                raise ValueError("Cannot symlink from URLs")
            # Given a URL, download it
            with TemporaryDirectory() as td:
                filename = urlparse(path).path.split('/')[-1]
                local_path = os.path.join(td, filename)
                if verbose >= 1:
                    print("downloading %s to %s" % (path, local_path))
                urlretrieve(path, local_path)
                # now install from the local copy
                install_nbextension(local_path,
                                    overwrite=overwrite,
                                    symlink=symlink,
                                    nbextensions_dir=nbext,
                                    verbose=verbose)
            continue

        # handle archives
        archive = None
        if path.endswith('.zip'):
            archive = zipfile.ZipFile(path)
        elif _safe_is_tarfile(path):
            archive = tarfile.open(path)

        if archive:
            if symlink:
                raise ValueError("Cannot symlink from archives")
            if verbose >= 1:
                print("extracting %s to %s" % (path, nbext))
            archive.extractall(nbext)
            archive.close()
            continue

        dest = pjoin(nbext, basename(path))
        if overwrite and os.path.exists(dest):
            if verbose >= 1:
                print("removing %s" % dest)
            if os.path.isdir(dest) and not os.path.islink(dest):
                shutil.rmtree(dest)
            else:
                os.remove(dest)

        if symlink:
            path = os.path.abspath(path)
            if not os.path.exists(dest):
                if verbose >= 1:
                    print("symlink %s -> %s" % (dest, path))
                os.symlink(path, dest)
            continue

        if os.path.isdir(path):
            strip_prefix_len = len(path) - len(basename(path))
            for parent, dirs, files in os.walk(path):
                dest_dir = pjoin(nbext, parent[strip_prefix_len:])
                if not os.path.exists(dest_dir):
                    if verbose >= 2:
                        print("making directory %s" % dest_dir)
                    os.makedirs(dest_dir)
                for file in files:
                    src = pjoin(parent, file)
                    # print("%r, %r" % (dest_dir, file))
                    dest = pjoin(dest_dir, file)
                    _maybe_copy(src, dest, verbose)
        else:
            src = path
            _maybe_copy(src, dest, verbose)
예제 #27
0
 def test_root_dir(self):
     with TemporaryDirectory() as td:
         fm = FileContentsManager(root_dir=td)
         self.assertEqual(fm.root_dir, td)
예제 #28
0
 def setup_class(cls):
     cls.td = TemporaryDirectory()
     cls.config.GenericFileCheckpoints.root_dir = cls.td.name
     super(PostgresContentsFileCheckpointsAPITest, cls).setup_class()
예제 #29
0
 def setUp(self):
     self._temp_dir = TemporaryDirectory()
     self.td = self._temp_dir.name
     self.contents_manager = FileContentsManager(root_dir=self.td, )
예제 #30
0
 def setup_class(cls):
     cls.td = TemporaryDirectory()
     cls.config = cls.make_config(cls.td)
     super(HybridContentsPGRootAPITest, cls).setup_class()