Beispiel #1
0
def _start_kernel():
    """starts the ipython kernel and returns the ipython app"""
    global _ipython_app, _kernel_running

    if _ipython_app and _kernel_running:
        return _ipython_app

    import IPython
    from ipykernel.kernelapp import IPKernelApp
    from zmq.eventloop import ioloop

    # patch IPKernelApp.start so that it doesn't block
    def _IPKernelApp_start(self):
        if self.poller is not None:
            self.poller.start()
        self.kernel.start()

        # set up a timer to periodically poll the zmq ioloop
        loop = ioloop.IOLoop.instance()

        def poll_ioloop(timer_id, time):
            global _kernel_running

            # if the kernel has been closed then run the event loop until it gets to the
            # stop event added by IPKernelApp.shutdown_request
            if self.kernel.shell.exit_now:
                _log.debug("IPython kernel stopping (%s)" % self.connection_file)
                timer.kill_timer(timer_id)
                loop.start()
                _kernel_running = False
                return

            # otherwise call the event loop but stop immediately if there are no pending events
            loop.add_timeout(0, lambda: loop.add_callback(loop.stop))
            loop.start()

        global _kernel_running
        _kernel_running = True
        timer.set_timer(100, poll_ioloop)

    IPKernelApp.start = _IPKernelApp_start

    # IPython expects sys.__stdout__ to be set
    sys.__stdout__ = sys.stdout
    sys.__stderr__ = sys.stderr

    # call the API embed function, which will use the monkey-patched method above
    IPython.embed_kernel()

    _ipython_app = IPKernelApp.instance()

    # patch ipapp so anything else trying to get a terminal app (e.g. ipdb)
    # gets our IPKernalApp.
    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.instance = lambda: _ipython_app
    __builtins__["get_ipython"] = lambda: _ipython_app.shell

    return _ipython_app
Beispiel #2
0
    def run(self):
        namespace = {
            'config': self.config,
            'registry': self.config.registry,
            'settings': self.config.registry.settings,
        }

        with mock.patch('signal.signal'):
            IPython.embed_kernel(local_ns=namespace)
Beispiel #3
0
def launch_debug_using_ipython():
    # run this from a gdb session in order to create a 
    # ipython session one could connect to for gdb_python symbol
    # symbol support
    import IPython
    if not ZMQ:
        IPython.embed()
    else:
        IPython.embed_kernel()
        """
Beispiel #4
0
def _start_kernel():
    """starts the ipython kernel and returns the ipython app"""
    if sys._ipython_app and sys._ipython_kernel_running:
        return sys._ipython_app

    import IPython
    from ipykernel.kernelapp import IPKernelApp
    from zmq.eventloop import ioloop

    # patch IPKernelApp.start so that it doesn't block
    def _IPKernelApp_start(self):
        if self.poller is not None:
            self.poller.start()
        self.kernel.start()

        # set up a timer to periodically poll the zmq ioloop
        loop = ioloop.IOLoop.instance()

        def poll_ioloop(timer_id, time):
            # if the kernel has been closed then run the event loop until it gets to the
            # stop event added by IPKernelApp.shutdown_request
            if self.kernel.shell.exit_now:
                _log.debug("IPython kernel stopping (%s)" %
                           self.connection_file)
                timer.kill_timer(timer_id)
                loop.start()
                sys._ipython_kernel_running = False
                return

            # otherwise call the event loop but stop immediately if there are no pending events
            loop.add_timeout(0, lambda: loop.add_callback(loop.stop))
            loop.start()

        sys._ipython_kernel_running = True
        timer.set_timer(100, poll_ioloop)

    IPKernelApp.start = _IPKernelApp_start

    # IPython expects sys.__stdout__ to be set
    sys.__stdout__ = sys.stdout
    sys.__stderr__ = sys.stderr

    # call the API embed function, which will use the monkey-patched method above
    IPython.embed_kernel()

    sys._ipython_app = IPKernelApp.instance()

    # patch ipapp so anything else trying to get a terminal app (e.g. ipdb)
    # gets our IPKernalApp.
    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.instance = lambda: sys._ipython_app
    __builtins__["get_ipython"] = lambda: sys._ipython_app.shell

    return sys._ipython_app
Beispiel #5
0
    def thread_func():
        try:
            # create a new event loop and schedule setup_ipython
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.call_soon(setup_ipython)

            # this starts the event loop
            IPython.embed_kernel()
        except:
            event.set()
            raise
Beispiel #6
0
def ipython_embed_kernel(dut):
    """Start an interactive Python shell."""
    yield Timer(0)
    import IPython
    print(textwrap.dedent("""
    ###############################################################################
    Running IPython embed_kernel()

    You can now send this process into the background with "Ctrl-Z bg" and run
        jupyter console --existing
    or
        jupyter qtconsole --existing
    or
        jupyter console --existing kernel-{}.json
    ###############################################################################""".format(os.getpid())))
    IPython.embed_kernel()
Beispiel #7
0
def _do_start_shell(config):
    # Import db handle, session and other useful stuff to the shell's scope
    db = None
    if isinstance(config, ServiceDaemon):
        db = config.get_main_store()

    # so that there is a db session handy in the shell
    session = db.Session()

    # these are just useful to have in a dev. shell
    import IPython, traceback, inspect, sys
    from pprint import pprint, pformat

    header = (
        "Database handle is:           db\n"
        "There's also an open session: session\n"
        "Imported packages:  traceback, inspect, sys\n"
        "Imported functions: pprint(), pformat()"
    )

    # start the kind of shell requested by user
    if config.shell:
        return IPython.embed(header=header)

    if config.ikernel:
        return IPython.embed_kernel()
Beispiel #8
0
def keyboard(banner=None):
    ''' Function that mimics the matlab keyboard command '''
    # use exception trick to pick up the current frame
    try:
        raise None
    except:
        frame = sys.exc_info()[2].tb_frame.f_back
    print("# Ctrl-D  Use quit() to exit :) Happy debugging!")
    # evaluate commands in current namespace
    namespace = frame.f_globals.copy()
    namespace.update(frame.f_locals)
    try:
        import IPython
        IPython.embed_kernel(module=None,local_ns=namespace)
    except SystemExit:
        return
Beispiel #9
0
def keyboard(banner=None):
    ''' Function that mimics the matlab keyboard command '''
    # use exception trick to pick up the current frame
    try:
        raise None
    except:
        frame = sys.exc_info()[2].tb_frame.f_back
    print("# Ctrl-D  Use quit() to exit :) Happy debugging!")
    # evaluate commands in current namespace
    namespace = frame.f_globals.copy()
    namespace.update(frame.f_locals)
    try:
        import IPython
        IPython.embed_kernel(module=None, local_ns=namespace)
    except SystemExit:
        return
Beispiel #10
0
def ipython_embed_kernel(dut):
    """Start an interactive Python shell."""
    yield Timer(0)
    import IPython
    print(textwrap.dedent("""
    ###############################################################################
    Running IPython embed_kernel()

    You can now send this process into the background with "Ctrl-Z bg" and run
        jupyter console --existing
    or
        jupyter qtconsole --existing
    or
        jupyter console --existing kernel-{}.json
    ###############################################################################""".format(os.getpid())))
    IPython.embed_kernel()
    def run(self):
        """
        The function that runs when the "start" function is called.
        This is what python will do to start the worker thread and the
        IPython kernel in the background.  Users can access the ipython console  with 
        ipython console --existing kernel-<pid>.json

        where pid is the pid above
        """
        import IPython
        statusString = "Howdy! Starting  %d %s" % (self.x, self.name)
        self.writeStatus(statusString)

        t1 = threading.Thread(target=self.runScript, args=())
        t1.start()
        self.workerThread = t1
        IPython.embed_kernel()

        return "done"
Beispiel #12
0
def test99_ipython(dut):
    "embed IPython shell for interactive exploration"
    expecteq_reset()
    dut.cocotb_testnum = 99
    o = RocstarTester(dut)
    yield o.run_hello()
    skip = False
    try:
        text = open("skip_t99.txt").read().strip().upper()
        print "skip_t99.txt contents:", text
        if "Y" in text:
            skip = True
    except IOError:
        print "skip_t99.txt not found"
        pass
    if skip:
        print "skipping T99 IPython() invocation, due to 'skip_t99.txt'"
    else:
        import IPython
        IPython.embed_kernel()
    expecteq_fail_if_not_ok()
Beispiel #13
0
def ipython_kernel_thread(ip="127.0.0.1"):
    from unittest import mock
    import IPython
    from ipykernel.zmqshell import ZMQInteractiveShell
    from ipykernel import kernelapp
    kernelapp._ctrl_c_message = "Starting Ipython Kernel"
    from IPython.core.autocall import ZMQExitAutocall

    class KeepAlive(ZMQExitAutocall):
        def __call__(self, keep_alive=True):
            super().__call__(keep_alive)
    ZMQInteractiveShell.exiter = KeepAlive()

    if ip == "0.0.0.0":
        ip = "*"
    elif ip == "localhost":
        ip = "127.0.0.1"

    with mock.patch('signal.signal'):
        with mock.patch('ipykernel.kernelbase.signal'):
            IPython.embed_kernel()
Beispiel #14
0
def main(python_exe, throw_on_error=False):
    clean_up_environment_path()

    t = threading.Thread(target=runner, args=[python_exe])
    t.start()

    print("Running IPython embeded kernel")
    try:
        IPython.embed_kernel(
            local_ns=sys._getframe(1).f_locals,
            connection_file=str(connection_file),
        )
    except Exception as exp:
        print("Unable to embed IPython. Exception occured:")
        print(exp)
        if throw_on_error:
            raise exp
    finally:
        if sys.stdout:
            sys.stdout.flush()
        t.join()
Beispiel #15
0
def do_this(plpy,**kwargs):
    global DEBUG,EMBED

    _defaults = {'iter_round':'first','DEBUG':False,'EMBED':False}
    _defaults.update(kwargs)
    for k,v in _defaults.iteritems():
        if type(v)==str:
            exec('%s = """%s"""' % (k,v),globals())
        else:
            exec('%s = %s' % (k,v),globals())

    if DEBUG and type(DEBUG)==bool:
        DEBUG = 1
    elif DEBUG and type(DEBUG)==int:
        DEBUG = 3 if DEBUG>=3 else DEBUG
    else:
        print 'unknown DEBUG parameter input'

    import os,re

    # import sys
    # sys.path.append('/usr/local/lib/python2.7/dist-packages/pycharm-debug.egg')
    # import pydevd
    # pydevd.settrace('10.0.1.53', port=50003, stdoutToServer=True, stderrToServer=True)

    # import IPython as I
    # I.embed_kernel()

    # import ipdb
    # ipdb.set_trace()



    if DEBUG>=1:
        os.system("echo '\\n\\n'`date --utc` >> /tmp/tmpfile")


    def log_to_file(msg):
        # plpy.log(msg)
        _file = '/tmp/tmpfile'
        with open(_file,'a') as f:
            f.write(str(msg) + '\n')

    def run_query(**kwargs):

        qry_a = """ SELECT
                        UPPER(CONCAT_WS('_',
                            %(concat)s
                            )) a_str,
                        ts_uid a_idx,
                        ts_div_line
                    FROM str_matching
                    %(cond)s
                    ORDER BY uid
                """
        qry_b = """ SELECT DISTINCT
                        UPPER(CONCAT_WS('_',
                            %(concat)s
                            )) b_str,
                        uid b_idx
                    FROM sub_stations
                    %(cond)s
                    ORDER BY uid
                """

        _updated = False
        ra = plpy.execute( qry_a % {'concat':a_concat,'cond':a_str_idx_cond} )
        if not ra:
            if DEBUG>=1:
                log_to_file('--- ending run_iter early ---')
            return _updated,0
        # else...
        for r in ra:

            # TODO: when string comparisons begin to use only parts of strings, other data should be added
            # TODO: add conditional for iterating parts of a_str


            if a_updates.count(r["a_idx"]) \
                and exclude_new_matches_from_subsequent_searches:
                pass

            else:

                if DEBUG>=1:
                    log_to_file('----------ts_uid: %(a_idx)s' % r)

                for k,v in r.iteritems():

                    # FIRST
                    # check if even number of single-quotes
                    if str(v).count("'") % 2==0:
                        pass

                    # HACK -- replace right-most single-quote with 2 single-quotes
                    else:
                        pt = v.rfind("'")
                        r[k] = v[:pt] + "'" + v[pt:]

                    # SECOND
                    # since r is passed through 2 layers of substitution:
                    #   (1) first when creating qry variable, and
                    #   (2) within function z_string_matching called by qry
                    # then:
                    #   "'" --> "''''"
                    if str(v).count("'"):
                        r[k] = re.sub(r"'{1}","''''",v)

                _t = {
                    'f_qry_a':qry_a.replace("'","''")
                          % {'concat':a_concat.replace("'","''").replace('\\','\\\\'),
                             'cond':a_str_cond.replace("'","''") }
                                % r,

                    'f_qry_b':qry_b.replace("'","''")
                          % {'concat':b_concat.replace("'","''").replace('\\','\\\\'),
                             'cond':b_str_cond.replace("'","''") }
                                % r,

                    'res_cond':result_cond
                    'params_as_json' : params_as_json
                     }

                qry =   """
                        WITH qry AS (
                            SELECT (z).*
                            FROM z_string_matching(
                                E'%(f_qry_a)s'::text,
                                E'%(f_qry_b)s'::text,
                                E'%(params_as_json)s'
                                ) z
                        )
                        ,str_matching_form as (
                            select
                                _str.ts_uid,_str.ts_div_line,_str.ts_station
                                ,z.a_str ts_str,
                                    z.jaro_score::DOUBLE PRECISION,
                                    z.b_str match_str
                                ,_stat.station_name sub_station,
                                    div_line sub_div_line,
                                    z.b_idx::INTEGER sub_idx
                                ,z.other_matches
                            FROM qry z
                            INNER JOIN str_matching _str
                            ON _str.ts_uid = z.a_idx::INTEGER
                            INNER JOIN sub_stations _stat
                            ON _stat.uid = z.b_idx::INTEGER
                            %(res_cond)s
                        )
                        ,upd AS (
                            UPDATE str_matching _str
                            SET
                                ts_str=_res.ts_str,
                                jaro_score=_res.jaro_score,
                                match_str=_res.match_str,
                                sub_station=_res.sub_station,
                                sub_div_line=_res.sub_div_line,
                                sub_idx=_res.sub_idx
                            FROM  str_matching_form _res
                            WHERE _res.ts_uid=_str.ts_uid
                            AND _res.jaro_score > _str.jaro_score
                            RETURNING uid
                        )
                        SELECT * FROM str_matching_form
                        """ % _t


                q_res = plpy.execute(qry)

                if q_res:
                    if DEBUG>=1:
                        log_to_file("found")

                    _updated = True

                if DEBUG>=1:
                    log_to_file(q_res)
                if DEBUG>=3:
                    log_to_file(qry)

                # TODO: remove
                if EMBED:
                    import ipdb
                    ipdb.set_trace()

                # break

        return _updated,r

    def mark_unmatched(r):
        qry = """    WITH upd AS (
                                SELECT uid
                                FROM str_matching
                                WHERE ts_uid=%(a_idx)s
                                AND jaro_score=0
                            )
                            UPDATE str_matching s
                            SET jaro_score=-1
                            FROM upd u
                            WHERE s.uid=u.uid;
              """ % r
        if DEBUG>=2:
            log_to_file('marking')
            log_to_file(r)

        plpy.execute(qry)


    def run_iter():

        # ITERATIONS:
        #   all permutations between a_str, b_str, and:
        #      station name,
        #      first half of station name split by "-",
        #      second half of station name split by "-",

        # TODO: fix below

        a_str_concat=['%s ts_station %s' % (a_prefix,a_suffix)]
        a_str_concat_partial=[
                      "%s REGEXP_REPLACE(ts_station,E'^([^-/]*)(-|/)(.*)$',E'\\1',E'g') %s" % (a_prefix,a_suffix),
                      "%s REGEXP_REPLACE(ts_station,E'^([^-/]*)(-|/)(.*)$',E'\\3',E'g') %s" % (a_prefix,a_suffix),
                      ]
        if iter_a_str_parts:
            a_str_concat.extend(a_str_concat_partial)

        b_str_concat=['%s station_name %s' % (b_prefix,b_suffix)]
        b_str_concat_partial=[
                      "%s REGEXP_REPLACE(station_name,E'^([^-/]*)(-|/)(.*)$',E'\\1',E'g') %s" % (b_prefix,b_suffix),
                      "%s REGEXP_REPLACE(station_name,E'^([^-/]*)(-|/)(.*)$',E'\\3',E'g') %s" % (b_prefix,b_suffix),
                      ]
        if iter_b_str_parts:
            b_str_concat.extend(b_str_concat_partial)

        # Note re: "\"
        #   each substitution interprets "\\" as "\"
        #   final log print of query before execution needs "\\\\" to read "\\"

        global a_concat,b_concat,a_updates
        a_updates,updated,end = [],False,False
        for i in range(len(a_str_concat)):
            a_concat = a_str_concat[i].replace('\\','\\\\')

            for j in range(len(b_str_concat)):
                b_concat = b_str_concat[j].replace('\\','\\\\')

                if DEBUG>=2:
                    log_to_file('Iterating str_concat (i,j) = (%s,%s)'%(i,j))

                res,r = run_query(a_concat=a_concat,b_concat=b_concat)
                if res:
                    updated = True
                    a_updates.append(r['a_idx'])
                elif not r:
                    end = True
                    break

                elif (not updated
                    and i==len(a_str_concat)-1
                    and j==len(b_str_concat)-1):
                        a_updates.append(r['a_idx'])
                        if DEBUG>=2:
                            log_to_file('MARKING UNMATCHED')
                        mark_unmatched(r)

                if end:
                    break
            if end:
                break


    a=0


    # First, all iterations are run where:
    #   (1) "a" queries limited to case where jaro_score = 0,
    #   (2) a_str and b_str are limited to station names
    #   (3) only b_str compared have same div_line as a_str ("strict_div_line"), and
    #   (4) only results with jaro_scores 0.95 and above are applied to str_matching


    # Second, similar to first except:
    #     no-emphasis on "division", and
    #     no limit on what results update str_matchingn


    # Third, all iteration run again, except where:
        #   (1) no strict matching for div_line
        #   (2) a_str and b_str now includes div_line
        #   (3) "a" queries limited to where jaro_score < 0.95
        #   (4) all results with higher scores replace in str_matching (default: 0.0)

    # TODO: Z.JARO_SCORE==SAME AND NEW RESULT HAS NUMBER
    global params_as_json
    global exclude_new_matches_from_subsequent_searches
    global iter_a_str_parts,iter_b_str_parts
    global iter_a_str_perms,iter_b_str_perms

    if iter_round=='first':
        a_prefix,a_suffix = '',''
        b_prefix,b_suffix = '',''

        iter_a_str_parts = False
        iter_b_str_parts = False

        iter_a_str_perms = False
        iter_b_str_perms = False

        a_str_idx_cond = ' WHERE jaro_score=0'            #  this relates to first_iter matching single 'a' results
        a_str_cond =' WHERE ts_uid=%(a_idx)s AND jaro_score>=0'
        exclude_new_matches_from_subsequent_searches = True

        b_str_cond =" WHERE div_line='%(ts_div_line)s'"
        result_cond = 'WHERE NOT z.jaro_score::DOUBLE PRECISION < 0.95'


        run_iter()

    elif iter_round=='second':
        res = plpy.execute("""WITH old AS (SELECT uid FROM str_matching WHERE jaro_score=-1) UPDATE str_matching s SET jaro_score=0 FROM old o WHERE o.uid = s.uid;""")
        a_prefix,a_suffix = '',''
        b_prefix,b_suffix = '',''

        iter_a_str_parts = False
        iter_b_str_parts = False

        iter_a_str_perms = False
        iter_b_str_perms = False

        a_str_idx_cond = ' WHERE jaro_score>=0 AND jaro_score<0.95'
        exclude_new_matches_from_subsequent_searches = False

        #TODO: remove
        a_str_idx_cond = ' WHERE jaro_score>=0 AND jaro_score<0.95 and ts_uid=47'

        a_str_cond = ' WHERE ts_uid=%(a_idx)s AND jaro_score>=0' #    jaro_score --> -1 when no matches in round 2



        _t =        {'name' : "station_name ~* '%(a_str)s'",
                     'div' : "split_part(div_line,'_',1)=SPLIT_PART('%(ts_div_line)s','_',1)",
                     'line' : "SPLIT_PART(div_line,'_',2)~*SPLIT_PART('%(ts_div_line)s','_',2)",
                    }

        b_str_conditions = [
                            # ' AND '.join([_t['name'],_t['div'],_t['line']]),
                            # ' AND '.join([_t['name'],_t['div']]),
                            # ' AND '.join([_t['name'],_t['line']]),
                            # order important for jaro-winkler score
                            # ' AND '.join([_t['div'],_t['line'],_t['name']]),
                            # ' AND '.join([_t['line'],_t['name']]),
                            # ' AND '.join([_t['div'],_t['name']]),
                            ''
                            # ' AND '.join([_t['div'],_t['line']]),
                            # _t['line'],
                           ]

        result_cond = ' WHERE z.jaro_score::DOUBLE PRECISION >= _str.jaro_score'

        for it in b_str_conditions:
            if DEBUG>=1:
                log_to_file('cond #: %s' % b_str_conditions.index(it))

            if it:
                b_str_cond = ' WHERE ' + it
            else:
                b_str_cond = ''

            if EMBED:
                import IPython as I
                I.embed_kernel()

            run_iter()

        # result_cond = ' WHERE z.jaro_score::DOUBLE PRECISION > _str.jaro_score::DOUBLE PRECISION'
        #
        # for it in b_str_conditions:
        #     log_to_file('cond #: %s' % b_str_conditions.index(it))
        #     b_str_cond = ' WHERE ' + it
        #     if EMBED:
        #         import IPython as I
        #         I.embed_kernel()
        #     run_iter()

    elif iter_round=='third':
        a_prefix,a_suffix = '',',ts_div_line'
        b_prefix,b_suffix = '',',div_line'
        a_str_idx_cond = ' WHERE jaro_score >= 0 AND jaro_score < 0.95'
        a_str_cond = ' WHERE ts_uid=%(a_idx)s AND jaro_score>=0'
        b_str_cond = " "
        result_cond = ' '
        run_iter()

    if DEBUG>=1:
        os.system("echo `date --utc`'\\nDONE' >> /tmp/tmpfile")
Beispiel #16
0
import IPython
IPython.embed_kernel(connection_file='kernel-emacs.json')
Beispiel #17
0
import IPython
a = 10

IPython.embed_kernel()

# then run: ipython console --existing kernel-XXXXX.json

Beispiel #18
0
def _block_on_repl(sig, frame):
    IPython.embed_kernel()
Beispiel #19
0
def _start_kernel():
    """starts the ipython kernel and returns the ipython app"""
    if sys._ipython_app and sys._ipython_kernel_running:
        return sys._ipython_app

    import IPython
    from ipykernel.kernelapp import IPKernelApp
    from zmq.eventloop import ioloop

    # patch IPKernelApp.start so that it doesn't block
    def _IPKernelApp_start(self):
        if self.poller is not None:
            self.poller.start()
        self.kernel.start()

        # set up a timer to periodically poll the zmq ioloop
        loop = ioloop.IOLoop.instance()

        def poll_ioloop(timer_id, time):
            # if the kernel has been closed then run the event loop until it gets to the
            # stop event added by IPKernelApp.shutdown_request
            if self.kernel.shell.exit_now:
                _log.debug("IPython kernel stopping (%s)" %
                           self.connection_file)
                timer.kill_timer(timer_id)
                loop.start()
                sys._ipython_kernel_running = False
                return

            # otherwise call the event loop but stop immediately if there are no pending events
            loop.add_timeout(0, lambda: loop.add_callback(loop.stop))
            loop.start()

        sys._ipython_kernel_running = True
        timer.set_timer(100, poll_ioloop)

    IPKernelApp.start = _IPKernelApp_start

    # IPython expects sys.__stdout__ to be set
    sys.__stdout__ = sys.stdout
    sys.__stderr__ = sys.stderr

    # call the API embed function, which will use the monkey-patched method above
    IPython.embed_kernel()

    ipy = IPKernelApp.instance()

    # Keep a reference to the kernel even if this module is reloaded
    sys._ipython_app = ipy

    # patch user_global_ns so that it always references the user_ns dict
    setattr(ipy.shell.__class__, 'user_global_ns',
            property(lambda self: self.user_ns))

    # patch ipapp so anything else trying to get a terminal app (e.g. ipdb) gets our IPKernalApp.
    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.instance = lambda: ipy
    __builtins__["get_ipython"] = lambda: ipy.shell.__class__

    # Use the inline matplotlib backend
    mpl = ipy.shell.find_magic("matplotlib")
    if mpl:
        mpl("inline")

    return ipy
Beispiel #20
0
 def run(self):
     IPython.embed_kernel(module=daemon_tools,
                          local_ns=daemon_tools.__dict__)
Beispiel #21
0
def _start_kernel():
    """starts the ipython kernel and returns the ipython app"""
    if sys._ipython_app and sys._ipython_kernel_running:
        return sys._ipython_app

    import IPython
    from ipykernel.kernelapp import IPKernelApp
    from zmq.eventloop import ioloop

    # patch IPKernelApp.start so that it doesn't block
    def _IPKernelApp_start(self):
        if self.poller is not None:
            self.poller.start()
        self.kernel.start()

        # set up a timer to periodically poll the zmq ioloop
        loop = ioloop.IOLoop.instance()

        def poll_ioloop(timer_id, time):
            # if the kernel has been closed then run the event loop until it gets to the
            # stop event added by IPKernelApp.shutdown_request
            if self.kernel.shell.exit_now:
                _log.debug("IPython kernel stopping (%s)" % self.connection_file)
                timer.kill_timer(timer_id)
                loop.start()
                sys._ipython_kernel_running = False
                return

            # otherwise call the event loop but stop immediately if there are no pending events
            loop.add_timeout(0, lambda: loop.add_callback(loop.stop))
            loop.start()

        sys._ipython_kernel_running = True
        timer.set_timer(100, poll_ioloop)

    IPKernelApp.start = _IPKernelApp_start

    # IPython expects sys.__stdout__ to be set
    sys.__stdout__ = sys.stdout
    sys.__stderr__ = sys.stderr

    # call the API embed function, which will use the monkey-patched method above
    IPython.embed_kernel()

    ipy = IPKernelApp.instance()

    # Keep a reference to the kernel even if this module is reloaded
    sys._ipython_app = ipy

    # patch user_global_ns so that it always references the user_ns dict
    setattr(ipy.shell.__class__, 'user_global_ns', property(lambda self: self.user_ns))

    # patch ipapp so anything else trying to get a terminal app (e.g. ipdb) gets our IPKernalApp.
    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.instance = lambda: ipy
    __builtins__["get_ipython"] = lambda: ipy.shell.__class__

    # Use the inline matplotlib backend
    mpl = ipy.shell.find_magic("matplotlib")
    if mpl:
        mpl("inline")

    return ipy
Beispiel #22
0
 def run(self):
     try:
         IPython.embed_kernel(module=daemon_tools,
                              local_ns=daemon_tools.__dict__)
     except:
         print("Unable to Start IPython kernel")
 def run(self):
     IPython.embed_kernel(module=daemon_tools, local_ns=daemon_tools.__dict__)
 def run(self):
     try:
         IPython.embed_kernel(module=daemon_tools, local_ns=daemon_tools.__dict__)
     except:
         print("Unable to Start IPython kernel")
Beispiel #25
0
def show_or_exit(key):
    global off_screen
    global last_key
    global show
    global do_cmd
    # clear out old messages
    txt = ''

    # set the progress bar visibility, so info can set it just once
    pbh = K.pbh
    pbh.send(show)
    displayed_columns = K.displayed_columns
    cols = K.cols

    if isinstance(K.loop.widget, urwid.Overlay):
        K.loop.widget = K.loop.widget[0] # pop off the overlay
    if key != '.':
        last_key = key
    else:
        key = last_key
    if key in k_quit:
        raise urwid.ExitMainLoop()
    elif key in k_help:
        display_help()
        return True
    elif key in k_version:
        #display_version()
        display_help()
        return True
    elif key in k_prev_one:
        #off_screen.append(cols.contents.pop())
        if off_screen:
            new_first = off_screen.pop()
            cols.contents.insert(0, new_first)
            cols.focus_position=0
    elif key in k_prev:
        #off_screen.append(cols.contents.pop())
        for x in range(displayed_columns):
            if off_screen:
                new_first = off_screen.pop()
                cols.contents.insert(0, new_first)
                cols.focus_position=0
    elif key in k_top:
        # take it from the top
        cols.contents = off_screen + cols.contents
        off_screen = []
        cols.focus_position=0
    elif key in k_end:
        # this is the end, my friends, the end, the end.
        off_screen.extend(cols.contents)
        # backfill here properly - fill the hole screen (add back as many columns as can be displayed)
        cols.contents = [off_screen.pop() for x in range(displayed_columns) ][::-1]
        txt = '(END)'
    elif key in k_next_one:
        if len(cols.contents) > displayed_columns:
            off_screen.append(cols.contents.pop(0))
        if len(cols.contents) == displayed_columns:
            txt = '(END)'
    elif key in k_next:
        for x in range(displayed_columns):
            if len(cols.contents) > displayed_columns:
                off_screen.append(cols.contents.pop(0))
        if len(cols.contents) == displayed_columns:
            txt = '(END)'
    elif key in k_search:
        #cmd_line_text.focus()
        K.all.set_focus('footer')
        txt = '/'
        #do_cmd = lambda x: rehighlight(K.txts, x)
        do_cmd = get_search_or_search_next(k_next_search)
        K.cmd_line_text.set_edit_text('')
    elif key in k_search_bw:
        #cmd_line_text.focus()
        K.all.set_focus('footer')
        txt = '?'
        do_cmd = get_search_or_search_next(k_prev_search)
        K.cmd_line_text.set_edit_text('')
    elif key in k_command:
        #txt = ':'
        c(':')
        K.all.set_focus('footer')
        #cmd_line_text.set_edit_text('')
        do_cmd = colon
        return
    elif key in k_submit:
        if K.all.get_focus() == 'footer':
            input = K.cmd_line_text.get_edit_text()
            K.cmd_line_text.set_edit_text('');
            K.all.set_focus('body')
            if do_cmd(input):
                # colon_dispatch methods return true if the rest of the method
                # should be skipped (because colon_dispatch method also calls
                # it, for example) 
                return
    elif key in k_escape:
        if K.all.get_focus() == 'footer':
            txt = ''
            K.all.set_focus('body')
    elif key in k_next_search:
        # focus pane with a next result only if found
        # pseudocode:
        #   if current pane contains a matched element:
        #       go to the next pane that contains an element (or highlight the
        #       next match?)
        #
        c("next search functionality not implemented yet")
        return True
        pass
    elif key in k_prev_search:
        # focus last result only if found
        c("prev search functionality not implemented yet")
        return True
        pass
    elif key in k_diff:
        rehighlight(K.txts, '', search=search_diff)
    elif key in k_diff_off:
        rehighlight(K.txts, '', search=search_noop)
    elif key in k_info:
        txt = K.fname
        if K.kanten_options['filetype']:
            txt += " (ft=" + K.kanten_options['filetype'] + ")"
        txt += " (%d / %d)" % (K.total_cols-len(cols.contents) +
                displayed_columns , K.total_cols)
        if len(cols.contents) == displayed_columns:
            txt += ' (END)'
        pbh.send(True)
    elif key in k_toggle_pbar:
        show = not show
        pbh.send(show)
    elif key in k_editor:
        editor = K.kanten_options['editor']
        os.spawnvp(os.P_WAIT, editor, [editor, K.fname])
    elif isinstance(key, tuple) and key[0] == "mouse press":
        if key[1] in  m_scroll_up:
            show_or_exit(k_next[0])
        elif key[1] in m_scroll_down: 
            show_or_exit(k_prev[0])
        elif key[1] in m_click: 
            column = xpos_to_col(key[-2])


            txt = "click in column %d, line %d" % (column, key[-1])
        elif key[1] in m_paste:
            txt = "we would paste X11 clipboard contents here"
        else:
            txt = "unhandled key " + str(key)
    elif key in k_debug:
        if DEBUG:
            IPython.embed_kernel()
    elif isinstance(key, tuple):
        txt = "unhandled key " + str(key)
    else:
        txt = "unhandled key " + str(key)
    if DEBUG:
        txt = "key = " + str(key)
    K.cmd_line_text.set_caption(txt)
    #cmd_line_text.set_edit_text(txt)
    K.pbar.set_completion(len(off_screen)+displayed_columns)
    K.cmd_line_text.set_edit_text('')