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


Python contextlib.redirect_stdout方法代碼示例

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


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

示例1: test_multiprocessing

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_multiprocessing(self):
        testargs = ['', '-j', '2', '-d', '-dt', 'yahoo', 'test']
        with patch.object(sys, 'argv', new=testargs):
            f1 = StringIO()
            with redirect_stdout(f1):
                main()

        testargs = ['', '-j', '-d', '-dt', 'yahoo', 'test']
        with patch.object(sys, 'argv', new=testargs):
            f2 = StringIO()
            with redirect_stdout(f2):
                main()

        testargs = ['', '-d', '-dt', 'yahoo', 'test']
        with patch.object(sys, 'argv', new=testargs):
            f3 = StringIO()
            with redirect_stdout(f3):
                main()

        result1 = f1.getvalue().strip()
        result2 = f2.getvalue().strip()
        result3 = f3.getvalue().strip()

        assert result1 == result2 == result3 
開發者ID:zdict,項目名稱:zdict,代碼行數:26,代碼來源:test_arguments.py

示例2: test_fconv_self_att_wp

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_fconv_self_att_wp(self):
        with contextlib.redirect_stdout(StringIO()):
            with tempfile.TemporaryDirectory('test_fconv_self_att_wp') as data_dir:
                create_dummy_data(data_dir)
                preprocess_translation_data(data_dir)
                config = [
                    '--encoder-layers', '[(512, 3)] * 2',
                    '--decoder-layers', '[(512, 3)] * 2',
                    '--decoder-attention', 'True',
                    '--encoder-attention', 'False',
                    '--gated-attention', 'True',
                    '--self-attention', 'True',
                    '--project-input', 'True',
                ]
                train_translation_model(data_dir, 'fconv_self_att_wp', config)
                generate_main(data_dir)

                # fusion model
                os.rename(os.path.join(data_dir, 'checkpoint_last.pt'), os.path.join(data_dir, 'pretrained.pt'))
                config.extend([
                    '--pretrained', 'True',
                    '--pretrained-checkpoint', os.path.join(data_dir, 'pretrained.pt'),
                    '--save-dir', os.path.join(data_dir, 'fusion_model'),
                ])
                train_translation_model(data_dir, 'fconv_self_att_wp', config) 
開發者ID:nusnlp,項目名稱:crosentgec,代碼行數:27,代碼來源:test_binaries.py

示例3: test_multiline_imports

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_multiline_imports():
    output = StringIO()
    with redirect_stdout(output), pytest.raises(SystemExit) as ex:
        similar.Run([MULTILINE, MULTILINE])
    assert ex.value.code == 0
    assert (
        output.getvalue().strip()
        == (
            """
8 similar lines in 2 files
==%s:0
==%s:0
   from foo import (
     bar,
     baz,
     quux,
     quuux,
     quuuux,
     quuuuux,
   )
TOTAL lines=16 duplicates=8 percent=50.00
"""
            % (MULTILINE, MULTILINE)
        ).strip()
    ) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:27,代碼來源:unittest_checker_similar.py

示例4: test_ignore_nothing

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_ignore_nothing():
    output = StringIO()
    with redirect_stdout(output), pytest.raises(SystemExit) as ex:
        similar.Run([SIMILAR1, SIMILAR2])
    assert ex.value.code == 0
    assert (
        output.getvalue().strip()
        == (
            """
5 similar lines in 2 files
==%s:0
==%s:0
   import one
   from two import two
   three
   four
   five
TOTAL lines=44 duplicates=5 percent=11.36
"""
            % (SIMILAR1, SIMILAR2)
        ).strip()
    ) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:24,代碼來源:unittest_checker_similar.py

示例5: test_working_example

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_working_example(self):
        instance = MyClass2()
        capture = io.StringIO()

        with redirect_stdout(capture):
            NewMethod("External call")(instance, "first", "second")

        external = capture.getvalue()
        self.assertIsNotNone(self.pattern.match(external), repr(external))

        capture = io.StringIO()
        with redirect_stdout(capture):
            instance.method("first", "second")

        internal = capture.getvalue()
        self.assertIsNotNone(self.pattern.match(internal), repr(internal)) 
開發者ID:PacktPublishing,項目名稱:Clean-Code-in-Python,代碼行數:18,代碼來源:test_descriptors_cpython.py

示例6: test_max_positions

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_max_positions(self):
        with contextlib.redirect_stdout(StringIO()):
            with tempfile.TemporaryDirectory('test_max_positions') as data_dir:
                create_dummy_data(data_dir)
                preprocess_translation_data(data_dir)
                with self.assertRaises(Exception) as context:
                    train_translation_model(
                        data_dir, 'fconv_iwslt_de_en', ['--max-target-positions', '5'],
                    )
                self.assertTrue(
                    'skip this example with --skip-invalid-size-inputs-valid-test' in str(context.exception)
                )
                train_translation_model(
                    data_dir, 'fconv_iwslt_de_en',
                    ['--max-target-positions', '5', '--skip-invalid-size-inputs-valid-test'],
                )
                with self.assertRaises(Exception) as context:
                    generate_main(data_dir)
                generate_main(data_dir, ['--skip-invalid-size-inputs-valid-test']) 
開發者ID:pytorch,項目名稱:fairseq,代碼行數:21,代碼來源:test_binaries.py

示例7: test_cmlm_transformer

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_cmlm_transformer(self):
        with contextlib.redirect_stdout(StringIO()):
            with tempfile.TemporaryDirectory('test_cmlm_transformer') as data_dir:
                create_dummy_data(data_dir)
                preprocess_translation_data(data_dir, ['--joined-dictionary'])
                train_translation_model(data_dir, 'cmlm_transformer', [
                    '--apply-bert-init',
                    '--criterion', 'nat_loss',
                    '--noise', 'full_mask',
                    '--pred-length-offset',
                    '--length-loss-factor', '0.1'
                ], task='translation_lev')
                generate_main(data_dir, [
                    '--task', 'translation_lev',
                    '--iter-decode-max-iter', '9',
                    '--iter-decode-eos-penalty', '0',
                    '--print-step',
                ]) 
開發者ID:pytorch,項目名稱:fairseq,代碼行數:20,代碼來源:test_binaries.py

示例8: test_iterative_nonautoregressive_transformer

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_iterative_nonautoregressive_transformer(self):
        with contextlib.redirect_stdout(StringIO()):
            with tempfile.TemporaryDirectory('test_iterative_nonautoregressive_transformer') as data_dir:
                create_dummy_data(data_dir)
                preprocess_translation_data(data_dir, ['--joined-dictionary'])
                train_translation_model(data_dir, 'iterative_nonautoregressive_transformer', [
                    '--apply-bert-init', '--src-embedding-copy', '--criterion',
                    'nat_loss', '--noise', 'full_mask', '--stochastic-approx',
                    '--dae-ratio', '0.5', '--train-step', '3'
                ], task='translation_lev')
                generate_main(data_dir, [
                    '--task', 'translation_lev',
                    '--iter-decode-max-iter', '9',
                    '--iter-decode-eos-penalty', '0',
                    '--print-step',
                ]) 
開發者ID:pytorch,項目名稱:fairseq,代碼行數:18,代碼來源:test_binaries.py

示例9: test_mixture_of_experts

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_mixture_of_experts(self):
        with contextlib.redirect_stdout(StringIO()):
            with tempfile.TemporaryDirectory('test_moe') as data_dir:
                create_dummy_data(data_dir)
                preprocess_translation_data(data_dir)
                train_translation_model(data_dir, 'transformer_iwslt_de_en', [
                    '--task', 'translation_moe',
                    '--user-dir', 'examples/translation_moe/src',
                    '--method', 'hMoElp',
                    '--mean-pool-gating-network',
                    '--num-experts', '3',
                    '--encoder-layers', '2',
                    '--decoder-layers', '2',
                    '--encoder-embed-dim', '8',
                    '--decoder-embed-dim', '8',
                ])
                generate_main(data_dir, [
                    '--task', 'translation_moe',
                    '--user-dir', 'examples/translation_moe/src',
                    '--method', 'hMoElp',
                    '--mean-pool-gating-network',
                    '--num-experts', '3',
                    '--gen-expert', '0'
                ]) 
開發者ID:pytorch,項目名稱:fairseq,代碼行數:26,代碼來源:test_binaries.py

示例10: test_alignment

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_alignment(self):
        with contextlib.redirect_stdout(StringIO()):
            with tempfile.TemporaryDirectory('test_alignment') as data_dir:
                create_dummy_data(data_dir, alignment=True)
                preprocess_translation_data(data_dir, ['--align-suffix', 'align'])
                train_translation_model(
                    data_dir,
                    'transformer_align',
                    [
                        '--encoder-layers', '2',
                        '--decoder-layers', '2',
                        '--encoder-embed-dim', '8',
                        '--decoder-embed-dim', '8',
                        '--load-alignments',
                        '--alignment-layer', '1',
                        '--criterion', 'label_smoothed_cross_entropy_with_alignment'
                    ],
                    run_validation=True,
                )
                generate_main(data_dir) 
開發者ID:pytorch,項目名稱:fairseq,代碼行數:22,代碼來源:test_binaries.py

示例11: pcolor

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def pcolor(color, *args, **kwargs):
    """ proxy print arguments """
    output = sys.stdout if "file" not in kwargs else kwargs["file"]
    with contextlib.redirect_stdout(output):
        print(color, end="")
        print(*args, end="", **kwargs)
        print("\x1B[0m") 
開發者ID:nongiach,項目名稱:arm_now,代碼行數:9,代碼來源:utils.py

示例12: _call_catch_fmt

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def _call_catch_fmt(call, limit=None):
    stdout = io.StringIO()
    try:
        with redirect_stdout(stdout):
            result = call()
    except Exception as e:
            value = stdout.getvalue()
            fmt = '{}{}'.format(value, traceback.format_exc(limit))
    else:
        value = stdout.getvalue()
        fmt = (value or '') + ('' if result is None else result)
    return fmt 
開發者ID:irdumbs,項目名稱:Dumb-Cogs,代碼行數:14,代碼來源:repl.py

示例13: lookup_string_wrapper

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def lookup_string_wrapper(dict_class, word, args):
    import sys
    if args.force_color:
        utils.Color.set_force_color()
    else:
        utils.Color.set_force_color(sys.stdout.isatty())

    dictionary = dict_class(args)
    f = StringIO()
    with redirect_stdout(f):
        dictionary.lookup(word)
    return f.getvalue() 
開發者ID:zdict,項目名稱:zdict,代碼行數:14,代碼來源:zdict.py

示例14: test_multiprocessing_error

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def test_multiprocessing_error(self):
        with self.assertRaises(SystemExit):
            testargs = ['', '-j', '0', '-d', '-dt', 'yahoo', 'test']
            with patch.object(sys, 'argv', new=testargs):
                f1 = StringIO()
                with redirect_stdout(f1):
                    main()

        with self.assertRaises(SystemExit):
            testargs = ['', '-j', '-1', '-d', '-dt', 'yahoo', 'test']
            with patch.object(sys, 'argv', new=testargs):
                f1 = StringIO()
                with redirect_stdout(f1):
                    main() 
開發者ID:zdict,項目名稱:zdict,代碼行數:16,代碼來源:test_arguments.py

示例15: suppress_output

# 需要導入模塊: import contextlib [as 別名]
# 或者: from contextlib import redirect_stdout [as 別名]
def suppress_output():
    """suppress both stdout and stderr outputs"""
    if sys.version_info >= (3, 5):
        from contextlib import redirect_stdout, redirect_stderr
    else:

        class _RedirectStream(object):

            _stream = None

            def __init__(self, new_target):
                self._new_target = new_target
                self._old_targets = []

            def __enter__(self):
                self._old_targets.append(getattr(sys, self._stream))
                setattr(sys, self._stream, self._new_target)
                return self._new_target

            def __exit__(self, exctype, excinst, exctb):
                setattr(sys, self._stream, self._old_targets.pop())

        class redirect_stdout(_RedirectStream):
            _stream = "stdout"

        class redirect_stderr(_RedirectStream):
            _stream = "stderr"

    with TemporaryFile("wt") as file:
        with redirect_stdout(file):
            with redirect_stderr(file):
                yield 
開發者ID:tox-dev,項目名稱:tox,代碼行數:34,代碼來源:stdlib.py


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