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


Python io.capture_output方法代码示例

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


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

示例1: test_px_blocking

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_px_blocking(self):
        ip = get_ipython()
        v = self.client[-1:]
        v.activate()
        v.block=True

        ip.magic('px a=5')
        self.assertEqual(v['a'], [5])
        ip.magic('px a=10')
        self.assertEqual(v['a'], [10])
        # just 'print a' works ~99% of the time, but this ensures that
        # the stdout message has arrived when the result is finished:
        with capture_output() as io:
            ip.magic(
                'px import sys,time;print(a);sys.stdout.flush();time.sleep(0.2)'
            )
        out = io.stdout
        self.assertTrue('[stdout:' in out, out)
        self.assertFalse('\n\n' in out)
        self.assertTrue(out.rstrip().endswith('10'))
        self.assertRaisesRemote(ZeroDivisionError, ip.magic, 'px 1/0') 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:23,代码来源:test_magics.py

示例2: test_cellpx_block_args

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_cellpx_block_args(self):
        """%%px --[no]block flags work"""
        ip = get_ipython()
        v = self.client[-1:]
        v.activate()
        v.block=False
        
        for block in (True, False):
            v.block = block
            ip.magic("pxconfig --verbose")
            with capture_output() as io:
                ip.run_cell_magic("px", "", "1")
            if block:
                self.assertTrue(io.stdout.startswith("Parallel"), io.stdout)
            else:
                self.assertTrue(io.stdout.startswith("Async"), io.stdout)
            
            with capture_output() as io:
                ip.run_cell_magic("px", "--block", "1")
            self.assertTrue(io.stdout.startswith("Parallel"), io.stdout)

            with capture_output() as io:
                ip.run_cell_magic("px", "--noblock", "1")
            self.assertTrue(io.stdout.startswith("Async"), io.stdout) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:26,代码来源:test_magics.py

示例3: test_px_pylab

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_px_pylab(self):
        """%pylab works on engines"""
        ip = get_ipython()
        v = self.client[-1]
        v.block = True
        v.activate()
        
        with capture_output() as io:
            ip.magic("px %pylab inline")
        
        self.assertTrue("Populating the interactive namespace from numpy and matplotlib" in io.stdout, io.stdout)
        
        with capture_output() as io:
            ip.magic("px plot(rand(100))")
        
        self.assertTrue('Out[' in io.stdout, io.stdout)
        self.assertTrue('matplotlib.lines' in io.stdout, io.stdout) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:19,代码来源:test_magics.py

示例4: test_display_empty_streams_single

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_display_empty_streams_single(self):
        """empty stdout/err are not displayed (single result)"""
        self.minimum_engines(1)
        
        v = self.client[-1]
        ar = v.execute("print (5555)")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual('5555\n', io.stdout)

        ar = v.execute("a=5")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout, '') 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:test_asyncresult.py

示例5: test_display_empty_streams_type

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_display_empty_streams_type(self):
        """empty stdout/err are not displayed (groupby type)"""
        self.minimum_engines(1)
        
        v = self.client[:]
        ar = v.execute("print (5555)")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout.count('5555'), len(v), io.stdout)
        self.assertFalse('\n\n' in io.stdout, io.stdout)
        self.assertEqual(io.stdout.count('[stdout:'), len(v), io.stdout)

        ar = v.execute("a=5")
        ar.get(5)
        with capture_output() as io:
            ar.display_outputs()
        self.assertEqual(io.stderr, '')
        self.assertEqual(io.stdout, '') 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:22,代码来源:test_asyncresult.py

示例6: test_stdout

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_stdout(self):
        """ Does the in-process kernel correctly capture IO?
        """
        kernel = InProcessKernel()

        with capture_output() as io:
            kernel.shell.run_cell('print("foo")')
        self.assertEqual(io.stdout, 'foo\n')

        kc = BlockingInProcessKernelClient(kernel=kernel)
        kernel.frontends.append(kc)
        kc.shell_channel.execute('print("bar")')
        msg = get_stream_message(kc)
        self.assertEqual(msg['content']['data'], 'bar\n')

#-----------------------------------------------------------------------------
# Utility functions
#----------------------------------------------------------------------------- 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:test_kernel.py

示例7: testIgnoreErrorsDoesNotPropagate

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def testIgnoreErrorsDoesNotPropagate(self):
    run_cell_result = self.run_cell(
        textwrap.dedent("""
      %%shell --ignore-errors
      /bin/false
      """))
    captured_output = run_cell_result.output

    self.assertEqual('', captured_output.stderr)
    # IPython displays the result of the last statement executed (unless it is
    # None) with a "Out[1]: " prefix. When using io.capture_output(), older
    # versions of IPython don't appear to capture this prompt in the stdout
    # stream. Due to this, we don't assert anything about the stdout output. If
    # an error is thrown, then accessing the "_" variable will fail.
    result = self.ip.user_ns['_']
    self.assertEqual(1, result.returncode)
    self.assertEqual('', result.output) 
开发者ID:googlecolab,项目名称:colabtools,代码行数:19,代码来源:test_system_commands.py

示例8: test__run_query_dry_run_without_errors_is_silent

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test__run_query_dry_run_without_errors_is_silent():
    magics.context._credentials = None

    sql = "SELECT 17"

    client_patch = mock.patch(
        "google.cloud.bigquery.magics.bigquery.Client", autospec=True
    )

    job_config = job.QueryJobConfig()
    job_config.dry_run = True
    with client_patch as client_mock, io.capture_output() as captured:
        client_mock().query(sql).job_id = None
        magics._run_query(client_mock(), sql, job_config=job_config)

    assert len(captured.stderr) == 0
    assert len(captured.stdout) == 0 
开发者ID:googleapis,项目名称:python-bigquery,代码行数:19,代码来源:test_magics.py

示例9: test_bigquery_magic_dryrun_option_variable_error_message

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_bigquery_magic_dryrun_option_variable_error_message():
    ip = IPython.get_ipython()
    ip.extension_manager.load_extension("google.cloud.bigquery")
    magics.context.credentials = mock.create_autospec(
        google.auth.credentials.Credentials, instance=True
    )

    run_query_patch = mock.patch(
        "google.cloud.bigquery.magics._run_query",
        autospec=True,
        side_effect=exceptions.BadRequest("Syntax error in SQL query"),
    )

    sql = "SELECT SELECT 17 AS num"

    assert "q_job" not in ip.user_ns

    with run_query_patch, io.capture_output() as captured:
        ip.run_cell_magic("bigquery", "q_job --dry_run", sql)

    full_text = captured.stderr
    assert "Could not save output to variable 'q_job'." in full_text 
开发者ID:googleapis,项目名称:python-bigquery,代码行数:24,代码来源:test_magics.py

示例10: test_bigquery_magic_omits_tracebacks_from_error_message

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_bigquery_magic_omits_tracebacks_from_error_message():
    ip = IPython.get_ipython()
    ip.extension_manager.load_extension("google.cloud.bigquery")

    credentials_mock = mock.create_autospec(
        google.auth.credentials.Credentials, instance=True
    )
    default_patch = mock.patch(
        "google.auth.default", return_value=(credentials_mock, "general-project")
    )

    run_query_patch = mock.patch(
        "google.cloud.bigquery.magics._run_query",
        autospec=True,
        side_effect=exceptions.BadRequest("Syntax error in SQL query"),
    )

    with run_query_patch, default_patch, io.capture_output() as captured_io:
        ip.run_cell_magic("bigquery", "", "SELECT foo FROM WHERE LIMIT bar")

    output = captured_io.stderr
    assert "400 Syntax error in SQL query" in output
    assert "Traceback (most recent call last)" not in output
    assert "Syntax error" not in captured_io.stdout 
开发者ID:googleapis,项目名称:python-bigquery,代码行数:26,代码来源:test_magics.py

示例11: test_cellpx_groupby_engine

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_cellpx_groupby_engine(self):
        """%%px --group-outputs=engine"""
        ip = get_ipython()
        v = self.client[:]
        v.block = True
        v.activate()
        
        v['generate_output'] = generate_output
        
        with capture_output() as io:
            ip.run_cell_magic('px', '--group-outputs=engine', 'generate_output()')
        
        self.assertFalse('\n\n' in io.stdout)
        lines = io.stdout.splitlines()
        expected = [
            r'\[stdout:\d+\]',
            'stdout',
            'stdout2',
            r'\[output:\d+\]',
            r'IPython\.core\.display\.HTML',
            r'IPython\.core\.display\.Math',
            r'Out\[\d+:\d+\]:.*IPython\.core\.display\.Math',
            ] * len(v)
        
        self.assertEqual(len(lines), len(expected), io.stdout)
        for line,expect in zip(lines, expected):
            if isinstance(expect, str):
                expect = [expect]
            for ex in expect:
                self.assertTrue(re.search(ex, line) is not None, "Expected %r in %r" % (ex, line))
        
        self._check_generated_stderr(io.stderr, len(v)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:34,代码来源:test_magics.py

示例12: test_cellpx_groupby_order

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_cellpx_groupby_order(self):
        """%%px --group-outputs=order"""
        ip = get_ipython()
        v = self.client[:]
        v.block = True
        v.activate()
        
        v['generate_output'] = generate_output
        
        with capture_output() as io:
            ip.run_cell_magic('px', '--group-outputs=order', 'generate_output()')
        
        self.assertFalse('\n\n' in io.stdout)
        lines = io.stdout.splitlines()
        expected = []
        expected.extend([
            r'\[stdout:\d+\]',
            'stdout',
            'stdout2',
        ] * len(v))
        expected.extend([
            r'\[output:\d+\]',
            'IPython.core.display.HTML',
        ] * len(v))
        expected.extend([
            r'\[output:\d+\]',
            'IPython.core.display.Math',
        ] * len(v))
        expected.extend([
            r'Out\[\d+:\d+\]:.*IPython\.core\.display\.Math'
        ] * len(v))
        
        self.assertEqual(len(lines), len(expected), io.stdout)
        for line,expect in zip(lines, expected):
            if isinstance(expect, str):
                expect = [expect]
            for ex in expect:
                self.assertTrue(re.search(ex, line) is not None, "Expected %r in %r" % (ex, line))
        
        self._check_generated_stderr(io.stderr, len(v)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:42,代码来源:test_magics.py

示例13: test_cellpx_groupby_type

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_cellpx_groupby_type(self):
        """%%px --group-outputs=type"""
        ip = get_ipython()
        v = self.client[:]
        v.block = True
        v.activate()
        
        v['generate_output'] = generate_output
        
        with capture_output() as io:
            ip.run_cell_magic('px', '--group-outputs=type', 'generate_output()')
        
        self.assertFalse('\n\n' in io.stdout)
        lines = io.stdout.splitlines()
        
        expected = []
        expected.extend([
            r'\[stdout:\d+\]',
            'stdout',
            'stdout2',
        ] * len(v))
        expected.extend([
            r'\[output:\d+\]',
            r'IPython\.core\.display\.HTML',
            r'IPython\.core\.display\.Math',
        ] * len(v))
        expected.extend([
            (r'Out\[\d+:\d+\]', r'IPython\.core\.display\.Math')
        ] * len(v))
        
        self.assertEqual(len(lines), len(expected), io.stdout)
        for line,expect in zip(lines, expected):
            if isinstance(expect, str):
                expect = [expect]
            for ex in expect:
                self.assertTrue(re.search(ex, line) is not None, "Expected %r in %r" % (ex, line))
        
        self._check_generated_stderr(io.stderr, len(v)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:40,代码来源:test_magics.py

示例14: test_autopx_blocking

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_autopx_blocking(self):
        ip = get_ipython()
        v = self.client[-1]
        v.activate()
        v.block=True

        with capture_output() as io:
            ip.magic('autopx')
            ip.run_cell('\n'.join(('a=5','b=12345','c=0')))
            ip.run_cell('b*=2')
            ip.run_cell('print (b)')
            ip.run_cell('b')
            ip.run_cell("b/c")
            ip.magic('autopx')
        
        output = io.stdout
        
        self.assertTrue(output.startswith('%autopx enabled'), output)
        self.assertTrue(output.rstrip().endswith('%autopx disabled'), output)
        self.assertTrue('ZeroDivisionError' in output, output)
        self.assertTrue('\nOut[' in output, output)
        self.assertTrue(': 24690' in output, output)
        ar = v.get_result(-1)
        self.assertEqual(v['a'], 5)
        self.assertEqual(v['b'], 24690)
        self.assertRaisesRemote(ZeroDivisionError, ar.get) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:28,代码来源:test_magics.py

示例15: test_autopx_nonblocking

# 需要导入模块: from IPython.utils import io [as 别名]
# 或者: from IPython.utils.io import capture_output [as 别名]
def test_autopx_nonblocking(self):
        ip = get_ipython()
        v = self.client[-1]
        v.activate()
        v.block=False

        with capture_output() as io:
            ip.magic('autopx')
            ip.run_cell('\n'.join(('a=5','b=10','c=0')))
            ip.run_cell('print (b)')
            ip.run_cell('import time; time.sleep(0.1)')
            ip.run_cell("b/c")
            ip.run_cell('b*=2')
            ip.magic('autopx')
        
        output = io.stdout.rstrip()
        
        self.assertTrue(output.startswith('%autopx enabled'))
        self.assertTrue(output.endswith('%autopx disabled'))
        self.assertFalse('ZeroDivisionError' in output)
        ar = v.get_result(-2)
        self.assertRaisesRemote(ZeroDivisionError, ar.get)
        # prevent TaskAborted on pulls, due to ZeroDivisionError
        time.sleep(0.5)
        self.assertEqual(v['a'], 5)
        # b*=2 will not fire, due to abort
        self.assertEqual(v['b'], 10) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:29,代码来源:test_magics.py


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