當前位置: 首頁>>代碼示例>>Python>>正文


Python contextlib.redirect_stderr方法代碼示例

本文整理匯總了Python中contextlib.redirect_stderr方法的典型用法代碼示例。如果您正苦於以下問題:Python contextlib.redirect_stderr方法的具體用法?Python contextlib.redirect_stderr怎麽用?Python contextlib.redirect_stderr使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在contextlib的用法示例。


在下文中一共展示了contextlib.redirect_stderr方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _run_example

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def _run_example(self, example):
        if example.focus and self.fail_if_focused:
            raise AssertionError(
                "Focused example not allowed with --fail-if-focused"
                ". Please remove the focus to allow the test to run."
            )
        if self.quiet:
            stdout = io.StringIO()
            stderr = io.StringIO()
            example_exception = None
            with redirect_stdout(stdout), redirect_stderr(stderr):
                try:
                    _ExampleRunner(example, self.formatter).run()
                except BaseException as ex:
                    example_exception = ex
            if example_exception:
                if not isinstance(example_exception, Skip):
                    if stdout.getvalue():
                        print("stdout:\n{}".format(stdout.getvalue()))
                    if stderr.getvalue():
                        print("stderr:\n{}".format(stderr.getvalue()))
                raise example_exception
        else:
            _ExampleRunner(example, self.formatter).run() 
開發者ID:facebookincubator,項目名稱:TestSlide,代碼行數:26,代碼來源:runner.py

示例2: test_command_without_stdout_ok

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_command_without_stdout_ok(self):
        # TODO make it work under windows
        if os.name == 'nt':
            return

        f = io.StringIO()
        with redirect_stdout(f):
            launch_cmd_displays_output(self.cmd_ok, False, False)
        res = f.getvalue()
        self.assertEqual('.', res[:1])

        try:
            from contextlib import redirect_stderr
        except Exception:
            return

        f = io.StringIO()
        with redirect_stderr(f):
            launch_cmd_displays_output(self.cmd_ok, False, False)
        res = f.getvalue()
        self.assertEqual('', res) 
開發者ID:stakkr-org,項目名稱:stakkr,代碼行數:23,代碼來源:command_test.py

示例3: test_command_with_stdout_ok

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_command_with_stdout_ok(self):
        # TODO make it work under windows
        if os.name == 'nt':
            return

        f = io.StringIO()
        with redirect_stdout(f):
            launch_cmd_displays_output(self.cmd_ok, True, False)
        res = f.getvalue()
        self.assertEqual('coucou\n\n', res)

        try:
            from contextlib import redirect_stderr
        except Exception:
            return

        f = io.StringIO()
        with redirect_stderr(f):
            launch_cmd_displays_output(self.cmd_ok, True, False)
        res = f.getvalue()
        self.assertEqual('', res) 
開發者ID:stakkr-org,項目名稱:stakkr,代碼行數:23,代碼來源:command_test.py

示例4: test_command_with_stderr_no_stdout_ok

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_command_with_stderr_no_stdout_ok(self):
        # TODO make it work under windows
        if os.name == 'nt':
            return

        f = io.StringIO()
        with redirect_stdout(f):
            launch_cmd_displays_output(self.cmd_ok, False, True)
        res = f.getvalue()
        self.assertEqual('.', res[:1])

        try:
            from contextlib import redirect_stderr
        except Exception:
            return

        f = io.StringIO()
        with redirect_stderr(f):
            launch_cmd_displays_output(self.cmd_ok, False, True)
        res = f.getvalue()
        self.assertEqual('', res) 
開發者ID:stakkr-org,項目名稱:stakkr,代碼行數:23,代碼來源:command_test.py

示例5: test_command_without_stderr_and_stdout_err

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_command_without_stderr_and_stdout_err(self):
        # TODO make it work under windows
        if os.name == 'nt':
            return

        f = io.StringIO()
        with redirect_stdout(f):
            launch_cmd_displays_output(self.cmd_nook, False, False)
        res = f.getvalue()
        self.assertEqual('\n', res)

        try:
            from contextlib import redirect_stderr
        except Exception:
            return

        f = io.StringIO()
        with redirect_stderr(f):
            launch_cmd_displays_output(self.cmd_nook, False, False)
        res = f.getvalue()
        self.assertEqual('', res) 
開發者ID:stakkr-org,項目名稱:stakkr,代碼行數:23,代碼來源:command_test.py

示例6: test_command_without_stderr_but_stdout_err

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_command_without_stderr_but_stdout_err(self):
        # TODO make it work under windows
        if os.name == 'nt':
            return

        f = io.StringIO()
        with redirect_stdout(f):
            launch_cmd_displays_output(self.cmd_nook, True, False)
        res = f.getvalue()
        self.assertEqual('\n', res)

        try:
            from contextlib import redirect_stderr
        except Exception:
            return

        f = io.StringIO()
        with redirect_stderr(f):
            launch_cmd_displays_output(self.cmd_nook, True, False)
        res = f.getvalue()
        self.assertEqual('', res) 
開發者ID:stakkr-org,項目名稱:stakkr,代碼行數:23,代碼來源:command_test.py

示例7: test_command_with_stderr_no_stdout_err_loop

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_command_with_stderr_no_stdout_err_loop(self):
        # TODO make it work under windows
        if os.name == 'nt':
            return

        f = io.StringIO()
        with redirect_stdout(f):
            cmd = ['cat', 'w', 'r', 'o', 'n', 'g', 'f', 'i', 'l', 'e']
            launch_cmd_displays_output(cmd, False, True)
        res = f.getvalue()
        expected = re.compile(r'.*\.\.\. and more.*', re.MULTILINE)
        self.assertRegex(res, expected)

        try:
            from contextlib import redirect_stderr
        except Exception:
            return

        f = io.StringIO()
        with redirect_stderr(f):
            launch_cmd_displays_output(self.cmd_nook, False, True)
        res = f.getvalue()
        self.assertEqual('', res) 
開發者ID:stakkr-org,項目名稱:stakkr,代碼行數:25,代碼來源:command_test.py

示例8: test_train_word2vec_subword_jap

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_train_word2vec_subword_jap(self):
        path_corpus = "./tests/data/corpora/jap/tokenized/"
        path_word2chars = "./tests/data/corpora/jap/char2radical/char2radical.txt"
        sio = io.StringIO()
        with contextlib.redirect_stderr(sio):
            run_module('vecto.embeddings.train_word2vec',
                       ['--path_corpus', path_corpus, '--path_out', '/tmp/vecto/embeddings/', '--dimension', '5',
                        '--subword', 'sum', '--language', 'jap', '--min_gram', '1', '--max_gram', '1'])
            run_module('vecto.embeddings.train_word2vec',
                       ['--path_corpus', path_corpus, '--path_out', '/tmp/vecto/embeddings/', '--dimension', '5',
                        '--subword', 'sum', '--language', 'jap', '--min_gram', '1', '--max_gram', '1',
                        '--path_word2chars', path_word2chars])

            with self.assertRaises(RuntimeError):
                run_module('vecto.embeddings.train_word2vec',
                           ['--path_corpus', path_corpus + "NONEXISTING", '--path_out', '/tmp/vecto/embeddings/',
                            '--dimension', '5',
                            '--subword', 'sum', '--language', 'jap', '--min_gram', '1', '--max_gram', '1']) 
開發者ID:vecto-ai,項目名稱:vecto,代碼行數:20,代碼來源:test_training.py

示例9: setFontItemText

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def setFontItemText(self, fontItemInfo, fontItem):
        font = fontItemInfo.font
        if font is None:
            return
        stderr = io.StringIO()
        with contextlib.redirect_stderr(stderr):
            glyphs = font.getGlyphRunFromTextInfo(self.textInfo,
                                                  features=self.project.textSettings.features,
                                                  varLocation=self.project.textSettings.varLocation,
                                                  colorLayers=self.project.textSettings.enableColor)
        stderr = stderr.getvalue()
        if stderr:
            fontItem.writeCompileOutput(stderr)

        addBoundingBoxes(glyphs)
        fontItem.glyphs = glyphs
        charSelection = self.characterList.getSelection()
        if charSelection:
            with self.blockCallbackRecursion():
                fontItem.selection = fontItem.glyphs.mapCharsToGlyphs(charSelection) 
開發者ID:justvanrossum,項目名稱:fontgoggles,代碼行數:22,代碼來源:mainWindow.py

示例10: configure

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def configure(project=LOGGING_PROJECT):
    """Configures cloud logging

    This is called for all main calls. If a $LOGGING_PROJECT is environment
    variable configured, then STDERR and STDOUT are redirected to cloud
    logging.
    """
    if not project:
        sys.stderr.write('!! Error: The $LOGGING_PROJECT enviroment '
                         'variable is required in order to set up cloud logging. '
                         'Cloud logging is disabled.\n')
        return

    logging.basicConfig(level=logging.INFO)
    try:
        # if this fails, redirect stderr to /dev/null so no startup spam.
        with contextlib.redirect_stderr(io.StringIO()):
            client = glog.Client(project)
            client.setup_logging(logging.INFO)
    except:
        sys.stderr.write('!! Cloud logging disabled\n') 
開發者ID:mlperf,項目名稱:training_results_v0.5,代碼行數:23,代碼來源:cloud_logging.py

示例11: _exec_script

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def _exec_script(self, host_info, py_script) -> any:
        """
        Import an additional script and run it

        :param host_info: host information
        :param py_script: python script filename
        :return: script execution result
        """
        if isinstance(py_script, str) and py_script.endswith(".py"):
            full_path = self.base_path.joinpath(py_script)
            py_script_wo_extension = py_script.replace(".py", "")
            loader = SourceFileLoader("main", str(full_path))
            module = ModuleType(loader.name)
            loader.exec_module(module)
            script_result = {py_script_wo_extension: module.main(host_info)}
            if not self.mute:
                return script_result
            with redirect_stderr(None), redirect_stdout(None):
                return script_result 
開發者ID:sdnewhop,項目名稱:grinder,代碼行數:21,代碼來源:pyscriptexecutor.py

示例12: capture_output

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def capture_output():
    """
    Suppress all stdout and stderr into a single buffer.

    Use as a context manager.

    :returns: the output
    :rtype: io.StringIO

    >>> with capture_output() as output:
    ...     print('hello')
    >>> output.getvalue()
    'hello'
    """
    sio = TeeStringIO()
    with contextlib.redirect_stdout(sio), contextlib.redirect_stderr(sio):
        yield sio 
開發者ID:natashamjaques,項目名稱:neural_chat,代碼行數:19,代碼來源:testing_utils.py

示例13: capture_output

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def capture_output():
    """
    Context manager which suppresses all stdout and stderr, and combines them
    into a single io.StringIO.

    :returns: the output
    :rtype: io.StringIO

    >>> with capture_output() as output:
    ...     print('hello')
    >>> output.getvalue()
    'hello'
    """
    sio = TeeStringIO()
    with contextlib.redirect_stdout(sio), contextlib.redirect_stderr(sio):
        yield sio 
開發者ID:THUDM,項目名稱:KBRD,代碼行數:18,代碼來源:testing_utils.py

示例14: test_err

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_err(capfd):
    msg = "Something that should not show up in log"
    stream = StringIO()
    with redirect_stderr(stream):
        m.raw_err(msg)
    stdout, stderr = capfd.readouterr()
    assert stdout == ''
    assert stderr == msg
    assert stream.getvalue() == ''

    stream = StringIO()
    with redirect_stderr(stream):
        m.captured_err(msg)
    stdout, stderr = capfd.readouterr()
    assert stdout == ''
    assert stderr == ''
    assert stream.getvalue() == msg 
開發者ID:luigifreda,項目名稱:pyslam,代碼行數:19,代碼來源:test_iostream.py

示例15: test_redirect_both

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stderr [as 別名]
def test_redirect_both(capfd):
    msg = "StdOut"
    msg2 = "StdErr"

    stream = StringIO()
    stream2 = StringIO()
    with redirect_stdout(stream):
        with redirect_stderr(stream2):
            with m.ostream_redirect():
                m.raw_output(msg)
                m.raw_err(msg2)
    stdout, stderr = capfd.readouterr()
    assert stdout == ''
    assert stderr == ''
    assert stream.getvalue() == msg
    assert stream2.getvalue() == msg2 
開發者ID:luigifreda,項目名稱:pyslam,代碼行數:18,代碼來源:test_iostream.py


注:本文中的contextlib.redirect_stderr方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。