当前位置: 首页>>代码示例>>Python>>正文


Python NotebookNode.stream方法代码示例

本文整理汇总了Python中IPython.nbformat.current.NotebookNode.stream方法的典型用法代码示例。如果您正苦于以下问题:Python NotebookNode.stream方法的具体用法?Python NotebookNode.stream怎么用?Python NotebookNode.stream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IPython.nbformat.current.NotebookNode的用法示例。


在下文中一共展示了NotebookNode.stream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def run_cell(self, cell):
        '''
        Run a notebook cell and update the output of that cell in-place.
        '''
        logging.info('Running cell:\n%s\n', cell.input)
        self.shell.execute(cell.input)
        reply = self.shell.get_msg()
        status = reply['content']['status']
        if status == 'error':
            logging.info('Cell raised uncaught exception: %s', reply['content']['ename'])
        else:
            logging.info('Cell returned')

        outs = list()
        while True:
            try:
                msg = self.iopub.get_msg(timeout=1)
                if msg['msg_type'] == 'status':
                    if msg['content']['execution_state'] == 'idle':
                        break
            except Empty:
                # execution state should return to idle before the queue becomes empty,
                # if it doesn't, something bad has happened
                raise

            content = msg['content']
            msg_type = msg['msg_type']

            out = NotebookNode(output_type=msg_type)

            if 'execution_count' in content:
                cell['prompt_number'] = content['execution_count']
                out.prompt_number = content['execution_count']

            if msg_type in ['status', 'pyin']:
                continue
            elif msg_type == 'stream':
                out.stream = content['name']
                out.text = content['data']
            elif msg_type in ('display_data', 'pyout'):
                for mime, data in content['data'].iteritems():
                    try:
                        attr = self.MIME_MAP[mime]
                    except KeyError:
                        raise NotImplementedError('unhandled mime type: %s' % mime)
                    
                    setattr(out, attr, data)
            elif msg_type == 'pyerr':
                out.ename = content['ename']
                out.evalue = content['evalue']
                out.traceback = content['traceback']

                logging.log('\n'.join(content['traceback']))
            else:
                raise NotImplementedError('unhandled iopub message: %s' % msg_type)
            outs.append(out)
        cell['outputs'] = outs

        if status == 'error':
            raise NotebookError()
开发者ID:rgbkrk,项目名称:runipy,代码行数:62,代码来源:notebook_runner.py

示例2: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(shell, iopub, cell, output=False):

    shell.execute(cell.input)

    #shell.get_msg()  # timeout=20
    outs = []

    while True:

        try:
            msg = iopub.get_msg(timeout=0.1)
        except Empty:
            continue

        msg_type = msg['msg_type']

        if msg_type  == 'pyin':
            continue
        elif msg_type == 'clear_output':
            outs = []
            continue
        elif msg_type == 'status':
            if msg['content']['execution_state'] == 'idle':
                break
            else:
                outs = []
                continue

        content = msg['content']
        out = NotebookNode(output_type=msg_type)

        if msg_type == 'stream':
            out.stream = content['name']
            out.text = content['data']

            if output:
                print(out.texti)#, end="")

        elif msg_type in ('display_data', 'pyout'):
            out['metadata'] = content['metadata']
            for mime, data in content['data'].items():
                attr = mime.split('/')[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace('+xml', '').replace('plain', 'text')
                setattr(out, attr, data)
            if msg_type == 'pyout':
                out.prompt_number = content['execution_count']

        elif msg_type == 'pyerr':
            out.ename = content['ename']
            out.evalue = content['evalue']
            out.traceback = content['traceback']
        else:
            log.error("Unhandled iopub msg : ", msg_type)

        outs.append(out)

    return outs
开发者ID:meduz,项目名称:run_ipynbs,代码行数:60,代码来源:run_ipynbs.py

示例3: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(kc, cell):
    shell = kc.shell_channel
    iopub = kc.iopub_channel
    outputs = []

    shell.execute(cell.input)
    # wait for finish, maximum 20s
    try:
        shell.get_msg(timeout=10)
    except Empty:
        return outputs

    failures = 0
    messages = 0
    while True:
        try:
            reply = iopub.get_msg(timeout=0.2)
            messages += 1
        except Empty:
            break
        content = reply["content"]
        msg_type = reply["msg_type"]

        if msg_type in ("status", "pyin"):
            continue
        elif msg_type == "clear_output":
            outputs = []
            continue

        out = NotebookNode(output_type=msg_type)

        if msg_type == "stream":
            out.stream = content["name"]
            out.text = content["data"]
        elif msg_type in ("display_data", "pyout"):
            for mime, data in content["data"].iteritems():
                attr = mime.split("/")[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace("+xml", "").replace("plain", "text")
                setattr(out, attr, data)
            if msg_type == "pyout":
                out.prompt_number = content["execution_count"]
        elif msg_type == "pyerr":
            out.ename = content["ename"]
            out.evalue = content["evalue"]
            out.traceback = content["traceback"]
        else:
            print "unhandled iopub msg:", msg_type

        outputs.append(out)
    return outputs
开发者ID:ldfaiztt,项目名称:stats-lecture-notes,代码行数:53,代码来源:execute_and_save.py

示例4: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(shell, iopub, cell):
    stime = time.time()
    shell.execute(cell.input)
    # wait for finish or timeout (in seconds)
    shell.get_msg(timeout=120)
    outs = []
    
    elapsedtime = time.time() - stime
    print ' %.2f sec | cell done.\n%s' % (elapsedtime, str(cell.input)[:50])

    while True:
        try:
            msg = iopub.get_msg(timeout=1.0)
        except Empty:
            break
        msg_type = msg['msg_type']
        if msg_type in ('status', 'pyin'):
            continue
        elif msg_type == 'clear_output':
            outs = []
            continue
        
        content = msg['content']
        # print msg_type, content
        out = NotebookNode(output_type=msg_type)
        
        if msg_type == 'stream':
            out.stream = content['name']
            out.text = content['data']
        elif msg_type in ('display_data', 'pyout'):
            for mime, data in content['data'].iteritems():
                attr = mime.split('/')[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace('+xml', '').replace('plain', 'text')
                setattr(out, attr, data)
            if msg_type == 'pyout':
                #out.prompt_number = content['execution_count']
                #TODO: need to find better workaround
                pass
        elif msg_type == 'pyerr':
            out.ename = content['ename']
            out.evalue = content['evalue']
            out.traceback = content['traceback']
        else:
            print "unhandled iopub msg:", msg_type
        
        outs.append(out)
    return outs
开发者ID:dchouren,项目名称:thesis,代码行数:50,代码来源:ExecuteNotebook.py

示例5: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(km, cell):
    shell = km.shell_channel
    iopub = km.sub_channel
    # print "\n\ntesting:"
    # print cell.input
    msg_id = shell.execute(cell.input)
    # wait for finish, no maximum
    msg = get_child_msg(km, msg_id)
    execution_count = msg['content']['execution_count']
    outs = []
    
    while True:
        try:
            msg = iopub.get_msg(timeout=0.2)
        except Empty:
            break
        msg_type = msg['msg_type']
        if msg_type in ('status', 'pyin'):
            continue
        elif msg_type == 'clear_output':
            outs = []
            continue
        
        content = msg['content']
        # print msg_type, content
        out = NotebookNode(output_type=msg_type)
        
        if msg_type == 'stream':
            out.stream = content['name']
            out.text = content['data']
        elif msg_type in ('display_data', 'pyout'):
            for mime, data in content['data'].iteritems():
                attr = mime.split('/')[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace('+xml', '').replace('plain', 'text')
                setattr(out, attr, data)
            if msg_type == 'pyout':
                out.prompt_number = content['execution_count']
        elif msg_type == 'pyerr':
            out.ename = content['ename']
            out.evalue = content['evalue']
            out.traceback = content['traceback']
        else:
            print "unhandled iopub msg:", msg_type
        
        outs.append(out)
    return outs, execution_count
开发者ID:arokem,项目名称:nbutils,代码行数:49,代码来源:nbrun.py

示例6: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(shell, iopub, cell):
    # print cell.input
    shell.execute(cell.input)
    # wait for finish, maximum 48h
    shell.get_msg(timeout=172800)
    outs = []

    while True:
        try:
            msg = iopub.get_msg(timeout=0.2)
        except Empty:
            break
        msg_type = msg["msg_type"]
        if msg_type in ("status", "pyin"):
            continue
        elif msg_type == "clear_output":
            outs = []
            continue

        content = msg["content"]
        # print msg_type, content
        out = NotebookNode(output_type=msg_type)

        if msg_type == "stream":
            out.stream = content["name"]
            out.text = content["data"]
        elif msg_type in ("display_data", "pyout"):
            for mime, data in content["data"].iteritems():
                attr = mime.split("/")[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace("+xml", "").replace("plain", "text")
                setattr(out, attr, data)
            if msg_type == "pyout":
                # out.prompt_number = content['execution_count']
                # TODO: need to find better workaround
                pass
        elif msg_type == "pyerr":
            out.ename = content["ename"]
            out.evalue = content["evalue"]
            out.traceback = content["traceback"]
        else:
            print "unhandled iopub msg:", msg_type

        outs.append(out)
    return outs
开发者ID:sjsrey,项目名称:gds15,代码行数:47,代码来源:ipnbdoctest.py

示例7: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def run_cell(self, shell, iopub, cell, exec_count):
        outs = []
        shell.execute(cell.input)
        # hard-coded timeout, problem?
        shell.get_msg(timeout=90)
        cell.prompt_number = exec_count # msg["content"]["execution_count"]

        while True:
            try:
                # whats the assumption on timeout here?
                # is it asynchronous?
                msg = iopub.get_msg(timeout=.2)
            except Empty:
                break
            msg_type = msg["msg_type"]
            if msg_type in ["status" , "pyin"]:
                continue
            elif msg_type == "clear_output":
                outs = []
                continue

            content = msg["content"]
            out = NotebookNode(output_type=msg_type)

            if msg_type == "stream":
                out.stream = content["name"]
                out.text = content["data"]
            elif msg_type in ["display_data", "pyout"]:
                for mime, data in content["data"].iteritems():
                    attr = mime.split("/")[-1].lower()
                    # this gets most right, but fix svg+html, plain
                    attr = attr.replace('+xml', '').replace('plain', 'text')
                    setattr(out, attr, data)
                if msg_type == "pyout":
                    out.prompt_number = exec_count #content["execution_count"]
            elif msg_type == "pyerr":
                out.ename = content["ename"]
                out.evalue = content["evalue"]
                out.traceback = content["traceback"]
            else:
                print "unhandled iopub msg:", msg_type

            outs.append(out)

        return outs
开发者ID:Autodidact24,项目名称:statsmodels,代码行数:47,代码来源:nbgenerate.py

示例8: test_preprocess_code_cell_solution

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def test_preprocess_code_cell_solution(self):
        """Is the solution version of a code cell correctly preprocessed?"""
        self.preprocessor.solution = True
        self.preprocessor.toc = ""
        cell = self._create_code_cell()

        self.preprocessor._create_client()
        cell, resources = self.preprocessor.preprocess_cell(cell, {}, 1)
        self.preprocessor._shutdown_client()

        output = NotebookNode()
        output.stream = "stdout"
        output.text = "hello\n"
        output.output_type = "stream"

        assert cell.input == """# YOUR CODE HERE\nprint "hello\""""
        assert cell.outputs == [output]
        assert cell.prompt_number == 1
开发者ID:jarrah42,项目名称:original-nbgrader,代码行数:20,代码来源:test_assignment_preprocessor.py

示例9: run

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def run(self, cell, timeout = None):
        use_timeout = self.default_timeout
        if timeout is not None:
            use_timeout = timeout
        self.shell.execute(cell.input)
        self.shell.get_msg(timeout=use_timeout)
        outs = []

        while True:
            try:
                msg = self.iopub.get_msg(timeout=0.5)
            except Empty:
                break
            msg_type = msg['msg_type']
            if msg_type in ('status', 'pyin'):
                continue
            elif msg_type == 'clear_output':
                outs = []
                continue

            content = msg['content']
            out = NotebookNode(output_type=msg_type)

            if msg_type == 'stream':
                out.stream = content['name']
                out.text = content['data']
            elif msg_type in ('display_data', 'pyout'):
                out['metadata'] = content['metadata']
                for mime, data in content['data'].iteritems():
                    attr = mime.split('/')[-1].lower()
                    # this gets most right, but fix svg+html, plain
                    attr = attr.replace('+xml', '').replace('plain', 'text')
                    setattr(out, attr, data)
                if msg_type == 'pyout':
                    out.prompt_number = content['execution_count']
            elif msg_type == 'pyerr':
                out.ename = content['ename']
                out.evalue = content['evalue']
                out.traceback = content['traceback']
            else:
                print "unhandled iopub msg:", msg_type

            outs.append(out)
        return outs
开发者ID:bmiles,项目名称:assaytools,代码行数:46,代码来源:ipnbdoctest.py

示例10: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(km, cell, timeout=20):
    shell = km.shell_channel
    iopub = km.iopub_channel
    shell.execute(cell.input)
    shell.get_msg(timeout=timeout)

    outs = []
    while True:
        try:
            msg = iopub.get_msg(timeout=0.2)
        except Empty:
            break

        msg_type = msg['msg_type']
        if msg_type in ('status', 'pyin'):
            continue
        elif msg_type == 'clear_output':
            outs = []
            continue

        content = msg['content']
        out = NotebookNode(output_type=msg_type)

        if msg_type == 'stream':
            out.stream = content['name']
            out.txt = content['data']
        elif msg_type in ('display_data', 'pyout'):
            for mime, data in content['data'].items():
                attr = mime.split('/')[-1].lower()
                attr = attr.replace('+xml', '').replace('plain', 'text')
                setattr(out, attr, data)
            if msg_type == 'pyout':
                out.prompt_number = content['execution_count']
        elif msg_type == 'pyerr':
            out.ename = content['ename']
            out.evalue = content['evalue']
            out.traceback = content['traceback']
        else:
            print("unhandled iopub msg:", msg_type)

        outs.append(out)
        cell.outputs = outs

    return outs
开发者ID:jbn,项目名称:BatchNotebook,代码行数:46,代码来源:__init__.py

示例11: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
def run_cell(shell, iopub, cell):
    shell.execute(cell.input)
    # wait for finish, maximum 20s
    shell.get_msg(timeout=20)
    outs = []

    while True:
        try:
            msg = iopub.get_msg(timeout=0.2)
        except Empty:
            break
        msg_type = msg['msg_type']
        if msg_type in ('status', 'pyin'):
            continue
        elif msg_type == 'clear_output':
            outs = []
            continue

        content = msg['content']
        out = NotebookNode(output_type=msg_type)

        if msg_type == 'stream':
            out.stream = content['name']
            out.text = content['data']
        elif msg_type in ('display_data', 'pyout'):
            out['metadata'] = content['metadata']
            for mime, data in content['data'].items():
                attr = mime.split('/')[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace('+xml', '').replace('plain', 'text')
                setattr(out, attr, data)
            if msg_type == 'pyout':
                out.prompt_number = content['execution_count']
        elif msg_type == 'pyerr':
            out.ename = content['ename']
            out.evalue = content['evalue']
            out.traceback = content['traceback']
        elif msg_type not in ('comm_msg', 'comm_open'):
            print("unhandled iopub msg:", msg_type)

        outs.append(out)
    return outs
开发者ID:DanyaLagos,项目名称:hypergraph,代码行数:44,代码来源:notebook_utils.py

示例12: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def run_cell(self, cell):  # noqa: C901
        """Run a notebook cell and update the output of that cell in-place."""
        self.shell.execute(cell.input)
        reply = self.shell.get_msg()
        status = reply['content']['status']
        if status == 'error':
            traceback_text = ("Cell raised uncaught exception: \n"
                              "\n".join(reply['content']['traceback']))

        outs = []
        while True:
            msg = self.iopub.get_msg(timeout=1)
            msg_type = msg['msg_type']
            content = msg['content']

            if msg_type == 'status' and content['execution_state'] == 'idle':
                break

            # IPython 3.0.0-dev writes pyerr/pyout in the notebook format
            # but uses error/execute_result in the message spec. This does
            # the translation needed for tests to pass with IPython 3.0.0-dev
            notebook3_format_conversions = {
                'error': 'pyerr',
                'execute_result': 'pyout',
            }
            msg_type = notebook3_format_conversions.get(msg_type, msg_type)

            out = NotebookNode(output_type=msg_type)

            if 'execution_count' in content:
                cell['prompt_number'] = content['execution_count']
                out.prompt_number = content['execution_count']

            if msg_type in ('status', 'pyin', 'execute_input'):
                continue
            elif msg_type == 'stream':
                out.stream = content['name']
                out.text = content['data']
            elif msg_type in ('display_data', 'pyout'):
                for mime, data in content['data'].items():
                    try:
                        attr = self.MIME_MAP[mime]
                    except KeyError:
                        raise NotImplementedError(
                            'unhandled mime type: %s' % mime)
                    setattr(out, attr, data)
            elif msg_type == 'pyerr':
                out.ename = content['ename']
                out.evalue = content['evalue']
                out.traceback = content['traceback']
            elif msg_type == 'clear_output':
                outs = []
                continue
            else:
                raise NotImplementedError(
                    'unhandled iopub message: %s' % msg_type)
            outs.append(out)
        cell['outputs'] = outs

        if status == 'error':
            raise Exception(traceback_text)
开发者ID:CamZHU,项目名称:nengo,代码行数:63,代码来源:ipython.py

示例13: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def run_cell(self, cell):
        """
        Run a notebook cell and update the output of that cell in-place.
        """

        #Changes to ensure proper order of pylab and matplotlib
        if 'from pylab import *' in cell.input:
            cell.input = cell.input.replace('from pylab import *', '')
            cell.input = 'from pylab import *\n' + cell.input

        if 'import matplotlib\n' in cell.input:
            cell.input = cell.input.replace('import matplotlib\n', '\n')

        if self.first_cell:
            self.first_cell = False
            cell.input = 'import matplotlib\nmatplotlib.use(\'pgf\')\n' + cell.input

        cell.input = cell.input.replace('%matplotlib inline', '')

        logging.info('Running cell:\n%s\n', cell.input)
        self.kc.execute(cell.input)
        reply = self.kc.get_shell_msg()
        status = reply['content']['status']
        traceback_text = ''
        if status == 'error':
            traceback_text = 'Cell raised uncaught exception: \n' + \
                '\n'.join(reply['content']['traceback'])
            logging.info(traceback_text)
        else:
            logging.info('Cell returned')

        outs = list()
        while True:
            try:
                msg = self.kc.get_iopub_msg(timeout=1)
                if msg['msg_type'] == 'status':
                    if msg['content']['execution_state'] == 'idle':
                        break
            except Empty:
                # execution state should return to idle
                # before the queue becomes empty,
                # if it doesn't, something bad has happened
                raise

            content = msg['content']
            msg_type = msg['msg_type']

            # IPython 3.0.0-dev writes pyerr/pyout in the notebook format
            # but uses error/execute_result in the message spec. This does the
            # translation needed for tests to pass with IPython 3.0.0-dev
            notebook3_format_conversions = {
                'error': 'pyerr',
                'execute_result': 'pyout'
            }
            msg_type = notebook3_format_conversions.get(msg_type, msg_type)

            out = NotebookNode(output_type=msg_type)

            if 'execution_count' in content:
                cell['prompt_number'] = content['execution_count']
                out.prompt_number = content['execution_count']

            if msg_type in ('status', 'pyin', 'execute_input'):
                continue
            elif msg_type == 'stream':
                out.stream = content['name']
                # in msgspec 5, this is name, text
                # in msgspec 4, this is name, data
                if 'text' in content:
                    out.text = content['text']
                else:
                    out.text = content['data']
                #print(out.text, end='')
            elif msg_type in ('display_data', 'pyout'):
                for mime, data in content['data'].items():
                    try:
                        attr = self.MIME_MAP[mime]
                    except KeyError:
                        raise NotImplementedError(
                            'unhandled mime type: %s' % mime
                        )

                    setattr(out, attr, data)
                #print(data, end='')
            elif msg_type == 'pyerr':
                out.ename = content['ename']
                out.evalue = content['evalue']
                out.traceback = content['traceback']

                #logging.error('\n'.join(content['traceback']))
            elif msg_type == 'clear_output':
                outs = list()
                continue
            else:
                raise NotImplementedError(
                    'unhandled iopub message: %s' % msg_type
                )
            outs.append(out)
        cell['outputs'] = outs

#.........这里部分代码省略.........
开发者ID:kantale,项目名称:runipy,代码行数:103,代码来源:notebook_runner.py

示例14: run_cell

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def run_cell(self, cell):
        '''
        Run a notebook cell and update the output of that cell in-place.
        '''
        logging.info('Running cell:\n%s\n', cell.input)
        self.shell.execute(cell.input)
        reply = self.shell.get_msg()
        status = reply['content']['status']
        if status == 'error':
            traceback_text = 'Cell raised uncaught exception: \n' + \
                '\n'.join(reply['content']['traceback'])
            logging.info(traceback_text)
        else:
            logging.info('Cell returned')

        outs = list()
        while True:
            try:
                msg = self.iopub.get_msg(timeout=1)
                if msg['msg_type'] == 'status':
                    if msg['content']['execution_state'] == 'idle':
                        break
            except Empty:
                # execution state should return to idle before the queue becomes empty,
                # if it doesn't, something bad has happened
                raise

            content = msg['content']
            msg_type = msg['msg_type']

            # IPython 3.0.0-dev writes pyerr/pyout in the notebook format but uses
            # error/execute_result in the message spec. This does the translation
            # needed for tests to pass with IPython 3.0.0-dev
            notebook3_format_conversions = {
                'error': 'pyerr',
                'execute_result': 'pyout'
            }
            msg_type = notebook3_format_conversions.get(msg_type, msg_type)

            out = NotebookNode(output_type=msg_type)

            if 'execution_count' in content:
                cell['prompt_number'] = content['execution_count']
                out.prompt_number = content['execution_count']

            if msg_type in ('status', 'pyin', 'execute_input'):
                continue
            elif msg_type == 'stream':
                out.stream = content['name']
                out.text = content['data']
                #print(out.text, end='')
            elif msg_type in ('display_data', 'pyout'):
                for mime, data in content['data'].items():
                    try:
                        attr = self.MIME_MAP[mime]
                    except KeyError:
                        raise NotImplementedError('unhandled mime type: %s' % mime)

                    setattr(out, attr, data)
                #print(data, end='')
            elif msg_type == 'pyerr':
                out.ename = content['ename']
                out.evalue = content['evalue']
                out.traceback = content['traceback']

                #logging.error('\n'.join(content['traceback']))
            elif msg_type == 'clear_output':
                outs = list()
                continue
            else:
                raise NotImplementedError('unhandled iopub message: %s' % msg_type)
            outs.append(out)
        cell['outputs'] = outs

        if status == 'error':
            raise NotebookError(traceback_text)
开发者ID:BernhardKonrad,项目名称:runipy,代码行数:78,代码来源:notebook_runner.py

示例15: runtest

# 需要导入模块: from IPython.nbformat.current import NotebookNode [as 别名]
# 或者: from IPython.nbformat.current.NotebookNode import stream [as 别名]
    def runtest(self):
        """
        Run all the cell tests in one kernel without restarting.
        It is very common for ipython notebooks to run through assuming a
        single kernel.
        """
        # Execute the code from the current cell and get the msg_id
        # of the shell process.
        msg_id = self.parent.kernel.execute_cell_input(
            self.cell.input, allow_stdin=False)

        # Time for the reply of the cell execution
        timeout = 2000

        # This list stores the output information for the entire cell
        outs = []

        # Wait for the execution reply (we can see this in the msg_type)
        # This execution produces a dictionary where a status string can be
        # obtained: 'ok' OR 'error' OR 'abort'
        # We can also get how many cells have been executed
        # until here, with the 'execution_count' entry
        #self.parent.kernel.kc.get_shell_msg(timeout=timeout)

        while True:
            """
            The messages from the cell contain information such
            as input code, outputs generated
            and other messages. We iterate through each message
            until we reach the end of the cell.
            """
            try:
                # Get one message at a time, per code block inside the cell
                msg = self.parent.get_kernel_message(timeout=1.)

            except Empty:
                # This is not working: ! The code will not be checked
                # if the time is out (when the cell stops to be executed?)
                # raise NbCellError("Timeout of %d seconds exceeded"
                #                      " executing cell: %s" (timeout,
                #                                             self.cell.input))
                # Just break the loop when the output is empty
                break

            """
            Now that we have the output from a piece of code
            inside the cell,
            we want to compare the outputs of the messages
            to a reference output (the ones that are present before
            the notebook was executed)
            """

            # Firstly, get the msg type from the cell to know if
            # the output comes from a code
            # It seems that the type 'stream' is irrelevant
            msg_type = msg['msg_type']

            # REF:
            # execute_input: To let all frontends know what code is
            # being executed at any given time, these messages contain a
            # re-broadcast of the code portion of an execute_request,
            # along with the execution_count.
            if msg_type in ('status', 'execute_input'):
                continue

            # If there is no more output, continue with the executions
            # (it will break if it is empty, with the previous statements)
            #
            # REF:
            # This message type is used to clear the output that is
            # visible on the frontend
            # elif msg_type == 'clear_output':
            #     outs = []
            #     continue

            # I added the msg_type 'idle' condition (when the cell stops)
            # so we get a complete cell output
            # REF:
            # When the kernel starts to execute code, it will enter the 'busy'
            # state and when it finishes, it will enter the 'idle' state.
            # The kernel will publish state 'starting' exactly
            # once at process startup.
            elif (msg_type == 'clear_output'
                  and msg_type['execution_state'] == 'idle'):
                outs = []
                continue

            # WE COULD ADD HERE a condition for the 'error' message type
            # Making the test to fail

            """
            Now we get the reply from the piece of code executed
            and analyse the outputs
            """
            reply = msg['content']
            out = NotebookNode(output_type=msg_type)

            # Now check what type of output it is
            if msg_type == 'stream':
                out.stream = reply['name']
#.........这里部分代码省略.........
开发者ID:maxalbert,项目名称:pytest_validate_nb,代码行数:103,代码来源:plugin.py


注:本文中的IPython.nbformat.current.NotebookNode.stream方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。