• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python textwrap.dedent函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中textwrap.dedent函数的典型用法代码示例。如果您正苦于以下问题:Python dedent函数的具体用法?Python dedent怎么用?Python dedent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: test_uninstall_from_reqs_file

def test_uninstall_from_reqs_file():
    """
    Test uninstall from a requirements file.

    """
    env = reset_env()
    write_file('test-req.txt', textwrap.dedent("""\
        -e %s#egg=initools-dev
        # and something else to test out:
        PyLogo<0.4
        """ % local_checkout('svn+http://svn.colorstudy.com/INITools/trunk')))
    result = run_pip('install', '-r', 'test-req.txt')
    write_file('test-req.txt', textwrap.dedent("""\
        # -f, -i, and --extra-index-url should all be ignored by uninstall
        -f http://www.example.com
        -i http://www.example.com
        --extra-index-url http://www.example.com

        -e %s#egg=initools-dev
        # and something else to test out:
        PyLogo<0.4
        """ % local_checkout('svn+http://svn.colorstudy.com/INITools/trunk')))
    result2 = run_pip('uninstall', '-r', 'test-req.txt', '-y')
    assert_all_changes(
        result, result2, [env.venv/'build', env.venv/'src', env.scratch/'test-req.txt'])
开发者ID:adieu,项目名称:pip,代码行数:25,代码来源:test_uninstall.py


示例2: assert_fromfile

  def assert_fromfile(self, parse_func, expected_append=None, append_contents=None):
    def _do_assert_fromfile(dest, expected, contents):
      with temporary_file() as fp:
        fp.write(contents)
        fp.close()
        options = parse_func(dest, fp.name)
        self.assertEqual(expected, options.for_scope('fromfile')[dest])

    _do_assert_fromfile(dest='string', expected='jake', contents='jake')
    _do_assert_fromfile(dest='intvalue', expected=42, contents='42')
    _do_assert_fromfile(dest='dictvalue', expected={'a': 42, 'b': (1, 2)}, contents=dedent("""
      {
        'a': 42,
        'b': (
          1,
          2
        )
      }
      """))
    _do_assert_fromfile(dest='listvalue', expected=['a', '1', '2'], contents=dedent("""
      ['a',
       1,
       2]
      """))

    expected_append = expected_append or [1, 2, 42]
    append_contents = append_contents or dedent("""
      [
       1,
       2,
       42
      ]
      """)
    _do_assert_fromfile(dest='appendvalue', expected=expected_append, contents=append_contents)
开发者ID:jsoref,项目名称:pants,代码行数:34,代码来源:test_options.py


示例3: testSetGlobalStyle

  def testSetGlobalStyle(self):
    try:
      style.SetGlobalStyle(style.CreateChromiumStyle())
      unformatted_code = textwrap.dedent(u"""\
          for i in range(5):
           print('bar')
          """)
      expected_formatted_code = textwrap.dedent(u"""\
          for i in range(5):
            print('bar')
          """)
      uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
      self.assertCodeEqual(expected_formatted_code,
                           reformatter.Reformat(uwlines))
    finally:
      style.SetGlobalStyle(style.CreatePEP8Style())
      style.DEFAULT_STYLE = self.current_style

    unformatted_code = textwrap.dedent(u"""\
        for i in range(5):
         print('bar')
        """)
    expected_formatted_code = textwrap.dedent(u"""\
        for i in range(5):
            print('bar')
        """)
    uwlines = yapf_test_helper.ParseAndUnwrap(unformatted_code)
    self.assertCodeEqual(expected_formatted_code, reformatter.Reformat(uwlines))
开发者ID:joachimmetz,项目名称:yapf,代码行数:28,代码来源:reformatter_style_config_test.py


示例4: createInterfaceFile

def createInterfaceFile(className):
   fileText = createHeadingComment()
   fileText += textwrap.dedent('''\
   
            #ifndef ''' + className.upper() + '''_H
            #define ''' + className.upper() + '''_H
            
            class ''' + className + ''' 
            {
            public:
               virtual ~''' + className + '''() {};
            
            public: // signals
            
            public: // slots
            
            };
            
            #endif
            ''')
   fileText = textwrap.dedent(fileText)
   if os.path.isfile(className + '.h'):
      return
   file = open(className + '.h', 'w')
   file.write(fileText)
开发者ID:StrugglezX,项目名称:2013Project,代码行数:25,代码来源:newClassGenerator.py


示例5: test_load_from_file_with_local_overriding_global

    def test_load_from_file_with_local_overriding_global(self):
        # The config data in the local and global files is loaded correctly.
        # The local data will override the global one
        content = '''
            [A]
            a=1
            b=c

            [B]
            b=2'''
        site_path = touch(content=textwrap.dedent(content))
        os.environ["OQ_SITE_CFG_PATH"] = site_path
        content = '''
            [A]
            a=2
            d=e

            [D]
            c=d-1
            d=4'''
        local_path = touch(content=textwrap.dedent(content))
        os.environ["OQ_LOCAL_CFG_PATH"] = local_path
        config.cfg.cfg.clear()
        config.cfg._load_from_file()
        self.assertEqual(["A", "B", "D"],
                         sorted(config.cfg.cfg))
        self.assertEqual({"a": "2", "b": "c", "d": "e"},
                         config.cfg.cfg.get("A"))
        self.assertEqual({"b": "2"}, config.cfg.cfg.get("B"))
        self.assertEqual({"c": "d-1", "d": "4"}, config.cfg.cfg.get("D"))
开发者ID:marmarques,项目名称:oq-engine,代码行数:30,代码来源:utils_config_test.py


示例6: test_sibling_build_files_duplicates

  def test_sibling_build_files_duplicates(self):
    # This workspace is malformed, you can't shadow a name in a sibling BUILD file
    self.add_to_build_file('BUILD', dedent(
      """
      fake(name="base",
           dependencies=[
             ':foo',
           ])
      """))

    self.add_to_build_file('BUILD.foo', dedent(
      """
      fake(name="foo",
           dependencies=[
             ':bat',
           ])
      """))

    self.add_to_build_file('./BUILD.bar', dedent(
      """
      fake(name="base")
      """))

    with self.assertRaises(BuildFileParser.SiblingConflictException):
      base_build_file = FilesystemBuildFile(self.build_root, 'BUILD')
      self.build_file_parser.address_map_from_build_file(base_build_file)
开发者ID:moshez,项目名称:pants,代码行数:26,代码来源:test_build_file_parser.py


示例7: test_nested_namespaces

  def test_nested_namespaces(self):
    self.create_file('src/thrift/com/foo/one.thrift', contents=dedent("""
    namespace py foo.bar

    struct One {}
    """))
    self.create_file('src/thrift/com/foo/bar/two.thrift', contents=dedent("""
    namespace py foo.bar.baz

    struct Two {}
    """))
    one = self.make_target(spec='src/thrift/com/foo:one',
                           target_type=PythonThriftLibrary,
                           sources=['one.thrift', 'bar/two.thrift'])
    _, synthetic_target = self.generate_single_thrift_target(one)
    self.assertEqual({'foo/__init__.py',
                      'foo/bar/__init__.py',
                      'foo/bar/constants.py',
                      'foo/bar/ttypes.py',
                      'foo/bar/baz/__init__.py',
                      'foo/bar/baz/constants.py',
                      'foo/bar/baz/ttypes.py'},
                     set(synthetic_target.sources_relative_to_source_root()))
    self.assert_ns_package(synthetic_target, 'foo')
    self.assert_leaf_package(synthetic_target, 'foo/bar')
    self.assert_leaf_package(synthetic_target, 'foo/bar/baz')
开发者ID:foursquare,项目名称:pants,代码行数:26,代码来源:test_apache_thrift_py_gen.py


示例8: run

  def run(self):
    ##########################
    # Get a list of all known
    # tests that we can run.
    ##########################    
    all_tests = self.__gather_tests()

    ##########################
    # Setup client/server
    ##########################
    print textwrap.dedent("""
      =====================================================
        Preparing up Server and Client ...
      =====================================================
      """)
    self.__setup_server()
    self.__setup_client()

    ##########################
    # Run tests
    ##########################
    self.__run_tests(all_tests)

    ##########################
    # Parse results
    ##########################  
    if self.mode == "benchmark":
      print textwrap.dedent("""
      =====================================================
        Parsing Results ...
      =====================================================
      """)
      self.__parse_results(all_tests)

    self.__finish()
开发者ID:kriswuollett,项目名称:FrameworkBenchmarks,代码行数:35,代码来源:benchmarker.py


示例9: test_upgrade_from_reqs_file

def test_upgrade_from_reqs_file(script):
    """
    Upgrade from a requirements file.

    """
    script.scratch_path.join("test-req.txt").write(textwrap.dedent("""\
        PyLogo<0.4
        # and something else to test out:
        INITools==0.3
        """))
    install_result = script.pip(
        'install', '-r', script.scratch_path / 'test-req.txt'
    )
    script.scratch_path.join("test-req.txt").write(textwrap.dedent("""\
        PyLogo
        # and something else to test out:
        INITools
        """))
    script.pip(
        'install', '--upgrade', '-r', script.scratch_path / 'test-req.txt'
    )
    uninstall_result = script.pip(
        'uninstall', '-r', script.scratch_path / 'test-req.txt', '-y'
    )
    assert_all_changes(
        install_result,
        uninstall_result,
        [script.venv / 'build', 'cache', script.scratch / 'test-req.txt'],
    )
开发者ID:DanishKhakwani,项目名称:pip,代码行数:29,代码来源:test_install_upgrade.py


示例10: test_check_prog_input

    def test_check_prog_input(self):
        config, out, status = self.get_result(textwrap.dedent('''
            option("--with-ccache", nargs=1, help="ccache")
            check_prog("CCACHE", ("known-a",), input="--with-ccache")
        '''), ['--with-ccache=known-b'])
        self.assertEqual(status, 0)
        self.assertEqual(config, {'CCACHE': self.KNOWN_B})
        self.assertEqual(out, 'checking for ccache... %s\n' % self.KNOWN_B)

        script = textwrap.dedent('''
            option(env="CC", nargs=1, help="compiler")
            @depends("CC")
            def compiler(value):
                return value[0].split()[0] if value else None
            check_prog("CC", ("known-a",), input=compiler)
        ''')
        config, out, status = self.get_result(script)
        self.assertEqual(status, 0)
        self.assertEqual(config, {'CC': self.KNOWN_A})
        self.assertEqual(out, 'checking for cc... %s\n' % self.KNOWN_A)

        config, out, status = self.get_result(script, ['CC=known-b'])
        self.assertEqual(status, 0)
        self.assertEqual(config, {'CC': self.KNOWN_B})
        self.assertEqual(out, 'checking for cc... %s\n' % self.KNOWN_B)

        config, out, status = self.get_result(script, ['CC=known-b -m32'])
        self.assertEqual(status, 0)
        self.assertEqual(config, {'CC': self.KNOWN_B})
        self.assertEqual(out, 'checking for cc... %s\n' % self.KNOWN_B)
开发者ID:brendandahl,项目名称:positron,代码行数:30,代码来源:test_checks_configure.py


示例11: dedent

def dedent(text):
    """Equivalent of textwrap.dedent that ignores unindented first line.

    This means it will still dedent strings like:
    '''foo
    is a bar
    '''

    For use in wrap_paragraphs.
    """

    if text.startswith('\n'):
        # text starts with blank line, don't ignore the first line
        return textwrap.dedent(text)

    # split first line
    splits = text.split('\n',1)
    if len(splits) == 1:
        # only one line
        return textwrap.dedent(text)

    first, rest = splits
    # dedent everything but the first line
    rest = textwrap.dedent(rest)
    return '\n'.join([first, rest])
开发者ID:AlbertHilb,项目名称:ipython,代码行数:25,代码来源:text.py


示例12: test_good_txt_transcript

    def test_good_txt_transcript(self):
        good_sjson = _create_file(content=textwrap.dedent("""\
                {
                  "start": [
                    270,
                    2720
                  ],
                  "end": [
                    2720,
                    5430
                  ],
                  "text": [
                    "Hi, welcome to Edx.",
                    "Let&#39;s start with what is on your screen right now."
                  ]
                }
            """))

        _upload_sjson_file(good_sjson, self.item.location)
        self.item.sub = _get_subs_id(good_sjson.name)
        transcripts = self.item.get_transcripts_info()
        text, filename, mime_type = self.item.get_transcript(transcripts, transcript_format="txt")
        expected_text = textwrap.dedent("""\
            Hi, welcome to Edx.
            Let's start with what is on your screen right now.""")

        self.assertEqual(text, expected_text)
        self.assertEqual(filename, self.item.sub + '.txt')
        self.assertEqual(mime_type, 'text/plain; charset=utf-8')
开发者ID:cmscom,项目名称:edx-platform,代码行数:29,代码来源:test_video_handlers.py


示例13: test_py3k_commutative_with_config_disable

    def test_py3k_commutative_with_config_disable(self):
        module = join(HERE, 'regrtest_data', 'py3k_errors_and_warnings.py')
        rcfile = join(HERE, 'regrtest_data', 'py3k-disabled.rc')
        cmd = [module, "--msg-template='{msg}'", "--reports=n"]

        expected = textwrap.dedent("""
        ************* Module py3k_errors_and_warnings
        import missing `from __future__ import absolute_import`
        Use raise ErrorClass(args) instead of raise ErrorClass, args.
        Calling a dict.iter*() method
        print statement used
        """)
        self._test_output(cmd + ["--py3k"], expected_output=expected)

        expected = textwrap.dedent("""
        ************* Module py3k_errors_and_warnings
        Use raise ErrorClass(args) instead of raise ErrorClass, args.
        Calling a dict.iter*() method
        print statement used
        """)
        self._test_output(cmd + ["--py3k", "--rcfile", rcfile],
                          expected_output=expected)

        expected = textwrap.dedent("""
        ************* Module py3k_errors_and_warnings
        Use raise ErrorClass(args) instead of raise ErrorClass, args.
        print statement used
        """)
        self._test_output(cmd + ["--py3k", "-E", "--rcfile", rcfile],
                          expected_output=expected)

        self._test_output(cmd + ["-E", "--py3k", "--rcfile", rcfile],
                          expected_output=expected)
开发者ID:Marslo,项目名称:VimConfig,代码行数:33,代码来源:test_self.py


示例14: getMissingImportStr

def getMissingImportStr(modNameList):
    """
    Given a list of missing module names, returns a nicely-formatted message to the user
    that gives instructions on how to expand music21 with optional packages.


    >>> print(common.getMissingImportStr(['matplotlib']))
    Certain music21 functions might need the optional package matplotlib;
    if you run into errors, install it by following the instructions at
    http://mit.edu/music21/doc/installing/installAdditional.html
    
    >>> print(common.getMissingImportStr(['matplotlib', 'numpy']))
    Certain music21 functions might need these optional packages: matplotlib, numpy;
    if you run into errors, install them by following the instructions at
    http://mit.edu/music21/doc/installing/installAdditional.html    
    """
    if len(modNameList) == 0:
        return None
    elif len(modNameList) == 1:
        return textwrap.dedent(
            """\
                  Certain music21 functions might need the optional package %s;
                  if you run into errors, install it by following the instructions at
                  http://mit.edu/music21/doc/installing/installAdditional.html"""
            % modNameList[0]
        )
    else:
        return textwrap.dedent(
            """\
                   Certain music21 functions might need these optional packages: %s;
                   if you run into errors, install them by following the instructions at
                   http://mit.edu/music21/doc/installing/installAdditional.html"""
            % ", ".join(modNameList)
        )
开发者ID:bagratte,项目名称:music21,代码行数:34,代码来源:misc.py


示例15: test_api_token_authentication

    def test_api_token_authentication(self):
        # Given
        yaml_string = textwrap.dedent("""\
            authentication:
              kind: token
              api_token: ulysse
        """)

        # When
        config = Configuration.from_yaml_filename(StringIO(yaml_string))

        # Then
        self.assertFalse(config.use_webservice)
        self.assertEqual(config.auth, APITokenAuth("ulysse"))

        # Given
        yaml_string = textwrap.dedent("""\
            authentication:
              api_token: ulysse
        """)

        # When
        config = Configuration.from_yaml_filename(StringIO(yaml_string))

        # Then
        self.assertFalse(config.use_webservice)
        self.assertEqual(config.auth, APITokenAuth("ulysse"))
开发者ID:cguwilliams,项目名称:HmyApp,代码行数:27,代码来源:test_config.py


示例16: test_enum_positive

    def test_enum_positive(self):
        # type: () -> None
        """Positive enum test cases."""

        # Test int
        self.assert_bind(
            textwrap.dedent("""
        enums:
            foo:
                description: foo
                type: int
                values:
                    v1: 3
                    v2: 1
                    v3: 2
            """))

        # Test string
        self.assert_bind(
            textwrap.dedent("""
        enums:
            foo:
                description: foo
                type: string
                values:
                    v1: 0
                    v2: 1
                    v3: 2
            """))
开发者ID:bjori,项目名称:mongo,代码行数:29,代码来源:test_binder.py


示例17: test_files_cache

    def test_files_cache(self):
        # Given
        yaml_string = textwrap.dedent("""\
            files_cache: "/foo/bar"
        """)

        # When
        config = Configuration.from_yaml_filename(StringIO(yaml_string))

        # Then
        self.assertFalse(config.use_webservice)
        self.assertEqual(config.repository_cache, "/foo/bar")

        # Given
        yaml_string = textwrap.dedent("""\
            files_cache: "~/foo/bar/{PLATFORM}"
        """)

        # When
        config = Configuration.from_yaml_filename(StringIO(yaml_string))

        # Then
        self.assertFalse(config.use_webservice)
        self.assertEqual(config.repository_cache,
                         os.path.expanduser("~/foo/bar/{0}".format(custom_plat)))
开发者ID:cguwilliams,项目名称:HmyApp,代码行数:25,代码来源:test_config.py


示例18: test_struct_enum_negative

    def test_struct_enum_negative(self):
        # type: () -> None
        """Negative enum test cases."""

        test_preamble = textwrap.dedent("""
        enums:
            foo:
                description: foo
                type: int
                values:
                    v1: 0
                    v2: 1
        """)

        # Test array of enums
        self.assert_bind_fail(test_preamble + textwrap.dedent("""
        structs:
            foo1:
                description: foo
                fields:
                    foo1: array<foo>
            """), idl.errors.ERROR_ID_NO_ARRAY_ENUM)

        # Test default
        self.assert_bind_fail(test_preamble + textwrap.dedent("""
        structs:
            foo1:
                description: foo
                fields:
                    foo1:
                        type: foo
                        default: 1
            """), idl.errors.ERROR_ID_FIELD_MUST_BE_EMPTY_FOR_ENUM)
开发者ID:bjori,项目名称:mongo,代码行数:33,代码来源:test_binder.py


示例19: test_sibling_build_files

  def test_sibling_build_files(self):
    self.add_to_build_file('BUILD', dedent(
      """
      fake(name="base",
           dependencies=[
             ':foo',
           ])
      """))

    self.add_to_build_file('BUILD.foo', dedent(
      """
      fake(name="foo",
           dependencies=[
             ':bat',
           ])
      """))

    self.add_to_build_file('./BUILD.bar', dedent(
      """
      fake(name="bat")
      """))

    bar_build_file = FilesystemBuildFile(self.build_root, 'BUILD.bar')
    base_build_file = FilesystemBuildFile(self.build_root, 'BUILD')
    foo_build_file = FilesystemBuildFile(self.build_root, 'BUILD.foo')

    address_map = self.build_file_parser.address_map_from_build_file(bar_build_file)
    addresses = address_map.keys()
    self.assertEqual({bar_build_file, base_build_file, foo_build_file},
                     set([address.build_file for address in addresses]))
    self.assertEqual({'//:base', '//:foo', '//:bat'},
                     set([address.spec for address in addresses]))
开发者ID:moshez,项目名称:pants,代码行数:32,代码来源:test_build_file_parser.py


示例20: test_command_positive

    def test_command_positive(self):
        # type: () -> None
        """Positive command tests."""

        # Setup some common types
        test_preamble = textwrap.dedent("""
        types:
            string:
                description: foo
                cpp_type: foo
                bson_serialization_type: string
                serializer: foo
                deserializer: foo
                default: foo
        """)

        self.assert_bind(test_preamble + textwrap.dedent("""
            commands: 
                foo:
                    description: foo
                    namespace: ignored
                    strict: true
                    fields:
                        foo: string
            """))
开发者ID:bjori,项目名称:mongo,代码行数:25,代码来源:test_binder.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python textwrap.fill函数代码示例发布时间:2022-05-27
下一篇:
Python textutils.reflow函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap