Beispiel #1
0
    def parse_command_line(self, argv=None):
        """Parse the command line arguments."""
        argv = sys.argv[1:] if argv is None else argv

        if self.subcommands and len(argv) > 0:
            # we have subcommands, and one may have been specified
            subc, subargv = argv[0], argv[1:]
            if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
                # it's a subcommand, and *not* a flag or class parameter
                return self.initialize_subcommand(subc, subargv)
            
        if '-h' in argv or '--help' in argv or '--help-all' in argv:
            self.print_description()
            self.print_help('--help-all' in argv)
            self.exit(0)

        if '--version' in argv:
            self.print_version()
            self.exit(0)
        
        loader = KeyValueConfigLoader(argv=argv, aliases=self.aliases,
                                        flags=self.flags)
        try:
            config = loader.load_config()
            self.update_config(config)
        except (TraitError, ArgumentError) as e:
            self.print_description()
            self.print_help()
            self.log.fatal(str(e))
            self.exit(1)
        # store unparsed args in extra_args
        self.extra_args = loader.extra_args
Beispiel #2
0
    def parse_command_line(self, argv=None):
        """Parse the command line arguments."""
        argv = sys.argv[1:] if argv is None else argv

        if self.subcommands and len(argv) > 0:
            # we have subcommands, and one may have been specified
            subc, subargv = argv[0], argv[1:]
            if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands:
                # it's a subcommand, and *not* a flag or class parameter
                return self.initialize_subcommand(subc, subargv)

        if '-h' in argv or '--help' in argv or '--help-all' in argv:
            self.print_description()
            self.print_help('--help-all' in argv)
            self.exit(0)

        if '--version' in argv:
            self.print_version()
            self.exit(0)

        loader = KeyValueConfigLoader(argv=argv,
                                      aliases=self.aliases,
                                      flags=self.flags)
        try:
            config = loader.load_config()
            self.update_config(config)
        except (TraitError, ArgumentError) as e:
            self.print_description()
            self.print_help()
            self.log.fatal(str(e))
            self.exit(1)
        # store unparsed args in extra_args
        self.extra_args = loader.extra_args
Beispiel #3
0
 def test_basic(self):
     cl = KeyValueConfigLoader()
     argv = [s.strip('c.') for s in pyfile.split('\n')[2:-1]]
     config = cl.load_config(argv)
     self.assertEquals(config.a, 10)
     self.assertEquals(config.b, 20)
     self.assertEquals(config.Foo.Bar.value, 10)
     self.assertEquals(config.Foo.Bam.value, range(10))
     self.assertEquals(config.D.C.value, 'hi there')
Beispiel #4
0
 def test_basic(self):
     cl = KeyValueConfigLoader()
     argv = [s.strip('c.') for s in pyfile.split('\n')[2:-1]]
     config = cl.load_config(argv)
     self.assertEquals(config.a, 10)
     self.assertEquals(config.b, 20)
     self.assertEquals(config.Foo.Bar.value, 10)
     self.assertEquals(config.Foo.Bam.value, range(10))
     self.assertEquals(config.D.C.value, 'hi there')
Beispiel #5
0
 def test_extra_args(self):
     cl = KeyValueConfigLoader()
     with mute_warn():
         config = cl.load_config(['--a=5', 'b', '--c=10', 'd'])
     self.assertEquals(cl.extra_args, ['b', 'd'])
     self.assertEquals(config.a, 5)
     self.assertEquals(config.c, 10)
     with mute_warn():
         config = cl.load_config(['--', '--a=5', '--c=10'])
     self.assertEquals(cl.extra_args, ['--a=5', '--c=10'])
Beispiel #6
0
 def test_unicode_bytes_args(self):
     uarg = u'a=é'
     try:
         barg = uarg.encode(sys.stdin.encoding)
     except (TypeError, UnicodeEncodeError):
         raise SkipTest("sys.stdin.encoding can't handle 'é'")
     
     cl = KeyValueConfigLoader()
     config = cl.load_config([barg])
     self.assertEquals(config.a, u'é')
Beispiel #7
0
    def test_unicode_bytes_args(self):
        uarg = u'a=é'
        try:
            barg = uarg.encode(sys.stdin.encoding)
        except (TypeError, UnicodeEncodeError):
            raise SkipTest("sys.stdin.encoding can't handle 'é'")

        cl = KeyValueConfigLoader()
        config = cl.load_config([barg])
        self.assertEquals(config.a, u'é')
def km_from_string(s = PMX_IPYTHON_CONNECTION):
    """create kernel manager from IPKernelApp string
    such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11
    or just 'kernel-12345.json' for IPython 0.12
    """
    from os.path import join as pjoin
    from IPython.zmq.blockingkernelmanager import BlockingKernelManager
    from IPython.config.loader import KeyValueConfigLoader
    from IPython.zmq.kernelapp import kernel_aliases
    
    s = s.replace('--existing', '')
    if 'connection_file' in BlockingKernelManager.class_trait_names():
        from IPython.lib.kernel import find_connection_file
        # 0.12 uses files instead of a collection of ports
        # include default IPython search path
        # filefind also allows for absolute paths, in which case the search
        # is ignored
        try:
            # XXX: the following approach will be brittle, depending on what
            # connection strings will end up looking like in the future, and
            # whether or not they are allowed to have spaces. I'll have to sync
            # up with the IPython team to address these issues -pi
            if '--profile' in s:
                k,p = s.split('--profile')
                k = k.lstrip().rstrip() # kernel part of the string
                p = p.lstrip().rstrip() # profile part of the string
                fullpath = find_connection_file(k,p)
            else:
                fullpath = find_connection_file(s.lstrip().rstrip())
        except IOError as e:
            print(":IPython " + s + " failed", "Info")
            print("^-- failed '" + s + "' not found", "Error")
            return
        km = BlockingKernelManager(connection_file = fullpath)
        km.load_connection_file()
    else:
        if s == '':
            print(":IPython 0.11 requires the full connection string")
            return
        loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
        cfg = loader.load_config()['KernelApp']
        try:
            km = BlockingKernelManager(
                shell_address=(ip, cfg['shell_port']),
                sub_address=(ip, cfg['iopub_port']),
                stdin_address=(ip, cfg['stdin_port']),
                hb_address=(ip, cfg['hb_port']))
        except KeyError as e:
            print(":IPython " +s + " failed", "Info")
            print("^-- failed --"+e.message.replace('_port','')+" not specified", "Error")
            return
    km.start_channels()
    return km
Beispiel #9
0
    def parse_command_line(self, argv=None):
        """Parse the command line arguments."""
        argv = sys.argv[1:] if argv is None else argv

        if '-h' in argv or '--help' in argv:
            self.print_description()
            self.print_help()
            sys.exit(1)

        if '--version' in argv:
            self.print_version()
            sys.exit(1)
        
        loader = KeyValueConfigLoader(argv=argv, aliases=self.aliases,
                                        flags=self.flags)
        config = loader.load_config()
        self.update_config(config)
Beispiel #10
0
def km_from_string(s=''):
    """create kernel manager from IPKernelApp string
    such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11
    or just 'kernel-12345.json' for IPython 0.12
    """
    try:
        import IPython
    except ImportError:
        raise ImportError("Could not find IPython. " + _install_instructions)
    from IPython.config.loader import KeyValueConfigLoader
    try:
        from IPython.kernel import (
            KernelManager,
            find_connection_file,
        )
    except ImportError:
        #  IPython < 1.0
        from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
        from IPython.zmq.kernelapp import kernel_aliases
        try:
            from IPython.lib.kernel import find_connection_file
        except ImportError:
            # < 0.12, no find_connection_file
            pass
        
    global km, kc, send

    s = s.replace('--existing', '')
    if 'connection_file' in KernelManager.class_trait_names():
        # 0.12 uses files instead of a collection of ports
        # include default IPython search path
        # filefind also allows for absolute paths, in which case the search
        # is ignored
        try:
            # XXX: the following approach will be brittle, depending on what
            # connection strings will end up looking like in the future, and
            # whether or not they are allowed to have spaces. I'll have to sync
            # up with the IPython team to address these issues -pi
            if '--profile' in s:
                k,p = s.split('--profile')
                k = k.lstrip().rstrip() # kernel part of the string
                p = p.lstrip().rstrip() # profile part of the string
                fullpath = find_connection_file(k,p)
            else:
                fullpath = find_connection_file(s.lstrip().rstrip())
        except IOError as e:
            echo(":IPython " + s + " failed", "Info")
            echo("^-- failed '" + s + "' not found", "Error")
            return
        km = KernelManager(connection_file = fullpath)
        km.load_connection_file()
    else:
        if s == '':
            echo(":IPython 0.11 requires the full connection string")
            return
        loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
        cfg = loader.load_config()['KernelApp']
        try:
            km = KernelManager(
                shell_address=(ip, cfg['shell_port']),
                sub_address=(ip, cfg['iopub_port']),
                stdin_address=(ip, cfg['stdin_port']),
                hb_address=(ip, cfg['hb_port']))
        except KeyError as e:
            echo(":IPython " +s + " failed", "Info")
            echo("^-- failed --"+e.message.replace('_port','')+" not specified", "Error")
            return

    try:
        kc = km.client()
    except AttributeError:
        # 0.13
        kc = km
    kc.start_channels()
    send = kc.shell_channel.execute

    #XXX: backwards compatibility for IPython < 0.13
    import inspect
    sc = kc.shell_channel
    num_oinfo_args = len(inspect.getargspec(sc.object_info).args)
    if num_oinfo_args == 2:
        # patch the object_info method which used to only take one argument
        klass = sc.__class__
        klass._oinfo_orig = klass.object_info
        klass.object_info = lambda s,x,y: s._oinfo_orig(x)
    
    #XXX: backwards compatibility for IPython < 1.0
    if not hasattr(kc, 'iopub_channel'):
        kc.iopub_channel = kc.sub_channel

    # now that we're connect to an ipython kernel, activate completion
    # machinery, but do so only for the local buffer if the user added the
    # following line the vimrc:
    #   let g:ipy_completefunc = 'local'
    vim.command("""
        if g:ipy_completefunc == 'global'
            set completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'local'
            setl completefunc=CompleteIPython
        endif
        """)
    # also activate GUI doc balloons if in gvim
    vim.command("""
        if has('balloon_eval')
            set bexpr=IPythonBalloonExpr()
        endif
        """)
    set_pid()
    return km
Beispiel #11
0
 def test_unicode_args(self):
     cl = KeyValueConfigLoader()
     argv = [u'--a=épsîlön']
     with mute_warn():
         config = cl.load_config(argv)
     self.assertEquals(config.a, u'épsîlön')
Beispiel #12
0
 def test_extra_args(self):
     cl = KeyValueConfigLoader()
     config = cl.load_config(['a=5', 'b', 'c=10', 'd'])
     self.assertEquals(cl.extra_args, ['b', 'd'])
     self.assertEquals(config.a, 5)
     self.assertEquals(config.c, 10)
Beispiel #13
0
 def test_unicode_args(self):
     cl = KeyValueConfigLoader()
     argv = [u'a=épsîlön']
     config = cl.load_config(argv)
     self.assertEquals(config.a, u'épsîlön')
Beispiel #14
0
 def test_extra_args(self):
     cl = KeyValueConfigLoader()
     config = cl.load_config(['a=5', 'b', 'c=10', 'd'])
     self.assertEquals(cl.extra_args, ['b', 'd'])
     self.assertEquals(config.a, 5)
     self.assertEquals(config.c, 10)
Beispiel #15
0
                k = k.lstrip().rstrip() # kernel part of the string
                p = p.lstrip().rstrip() # profile part of the string
                fullpath = find_connection_file(k,p)
            else:
                fullpath = find_connection_file(s.lstrip().rstrip())
        except IOError,e:
            print ":IPython " + s + " failed", "Info"
            print "^-- failed '" + s + "' not found", "Error"
            return
        km = BlockingKernelManager(connection_file = fullpath)
        km.load_connection_file()
    else:
        if s == '':
            print ":IPython 0.11 requires the full connection string"
            return
        loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
        cfg = loader.load_config()['KernelApp']
        try:
            km = BlockingKernelManager(
                shell_address=(ip, cfg['shell_port']),
                sub_address=(ip, cfg['iopub_port']),
                stdin_address=(ip, cfg['stdin_port']),
                hb_address=(ip, cfg['hb_port']))
        except KeyError,e:
            print ":IPython " +s + " failed", "Info"
            print "^-- failed --"+e.message.replace('_port','')+" not specified", "Error"
            return
    km.start_channels()
    return km

kernelManager = km_from_string()