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


Python FilePath.children方法代码示例

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


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

示例1: test_functional_centos_7

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def test_functional_centos_7(self):
        """
        The expected RPM files are built for CentOS 7
        """
        output_dir = FilePath(self.mktemp())
        check_call([
            FLOCKER_PATH.descendant([b'admin', b'build-package']).path,
            '--destination-path', output_dir.path,
            '--distribution', 'centos-7',
            FLOCKER_PATH.path
        ])
        python_version = __version__
        rpm_version = make_rpm_version(python_version)

        expected_basenames = (
            ('clusterhq-python-flocker', 'x86_64'),
            ('clusterhq-flocker-cli', 'noarch'),
            ('clusterhq-flocker-node', 'noarch'),
        )
        expected_filenames = []
        for basename, arch in expected_basenames:
            f = '{}-{}-{}.{}.rpm'.format(
                basename, rpm_version.version, rpm_version.release, arch)
            expected_filenames.append(f)

        self.assertEqual(
            set(expected_filenames),
            set(f.basename() for f in output_dir.children())
        )

        for f in output_dir.children():
            assert_rpm_lint(self, f)
开发者ID:hanwoody,项目名称:flocker,代码行数:34,代码来源:test_packaging.py

示例2: test_functional_ubuntu_1404

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def test_functional_ubuntu_1404(self):
        """
        The expected deb files are generated on Ubuntu14.04.
        """
        output_dir = FilePath(self.mktemp())
        check_call([
            FLOCKER_PATH.descendant([b'admin', b'build-package']).path,
            '--destination-path', output_dir.path,
            '--distribution', 'ubuntu-14.04',
            FLOCKER_PATH.path
        ])
        python_version = __version__
        rpm_version = make_rpm_version(python_version)

        expected_basenames = (
            ('clusterhq-python-flocker', 'amd64'),
            ('clusterhq-flocker-cli', 'all'),
            ('clusterhq-flocker-node', 'all'),
        )
        expected_filenames = []
        for basename, arch in expected_basenames:
            f = '{}_{}-{}_{}.deb'.format(
                basename, rpm_version.version, rpm_version.release, arch)
            expected_filenames.append(f)

        self.assertEqual(
            set(expected_filenames),
            set(f.basename() for f in output_dir.children())
        )

        for f in output_dir.children():
            assert_deb_lint(self, f)
开发者ID:hanwoody,项目名称:flocker,代码行数:34,代码来源:test_packaging.py

示例3: main

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
def main(argv):
    # input
    posts = FilePath(argv[1])

    # output
    blog = FilePath(argv[2])

    # Since Sphinx gets confused by image paths with "special" characters in
    # them, generate new names for all the image paths and a mapping from the
    # old names to the new names.
    images = FilePath(argv[3])

    imagepaths = []
    for post in images.children():
        if post.isdir():
            imagepaths.append(post)
            safe = post.sibling(fixpath(post.basename()))
            if post != safe and not safe.isdir():
                post.moveTo(safe)
                safe.linkTo(post)

    entries = []
    for post in posts.children():
        data = post.getContent().decode("utf-8")
        ignored, header, body = data.split(b"---", 2)
        meta = dict((text.strip() for text in line.split(":", 1)) for line in header.splitlines() if line.strip())
        date = datetime.strptime(meta["date"], "%Y/%m/%d %H:%M:%S")

        parent = blog.preauthChild(
            ("%d/%02d/%02d" % (date.year, date.month, date.day)).encode("utf-8"))
        title = fixpath(meta["title"].strip().lower().encode("utf-8")).decode("utf-8")
        entry = parent.child((title + ".rst").encode("utf-8"))

        header = HEADER_TEMPLATE % dict(
            author=meta["author"].strip(), categories="none",
            tags=meta["categories"].strip(), title=meta["title"].strip(),
            underbar="=" * len(meta["title"].strip()))

        for path in imagepaths:
            body = body.replace(
                u"/" + path.basename().decode("utf-8") + u"/",
                u"/" + fixpath(path.basename()).decode("utf-8") + u"/")

        if not parent.isdir():
            parent.makedirs()

        entry.setContent((header + html2rst(body)).encode("utf-8"))

        entries.append(entry)

    entries.sort()
    entries.reverse()

    sitemap = SITEMAP % dict(
        entries="".join([
                "\n   " + "/".join(entry.segmentsFrom(blog))
                for entry in entries]))
    blog.child(b"master.rst").setContent(sitemap.encode("utf-8"))

    FilePath(b"conf.py").copyTo(blog.child(b"conf.py"))
开发者ID:exarkun,项目名称:blogofile2tinkerer,代码行数:62,代码来源:blogofile2tinkerer.py

示例4: test_alwaysPreferPy

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def test_alwaysPreferPy(self):
        """
        Verify that .py files will always be preferred to .pyc files, regardless of
        directory listing order.
        """
        mypath = FilePath(self.mktemp())
        mypath.createDirectory()
        pp = modules.PythonPath(sysPath=[mypath.path])
        originalSmartPath = pp._smartPath

        def _evilSmartPath(pathName):
            o = originalSmartPath(pathName)
            originalChildren = o.children

            def evilChildren():
                # normally this order is random; let's make sure it always
                # comes up .pyc-first.
                x = originalChildren()
                x.sort()
                x.reverse()
                return x

            o.children = evilChildren
            return o

        mypath.child("abcd.py").setContent("\n")
        compileall.compile_dir(mypath.path, quiet=True)
        # sanity check
        self.assertEquals(len(mypath.children()), 2)
        pp._smartPath = _evilSmartPath
        self.assertEquals(pp["abcd"].filePath, mypath.child("abcd.py"))
开发者ID:JDShu,项目名称:bravo,代码行数:33,代码来源:test_modules.py

示例5: test_catchAll

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
 def test_catchAll(self):
     """
     Everything should match a catchall rule.
     """
     tmpdir = FilePath(self.mktemp())
     rules = [
         {
             'pattern': {
                 'foo': '*',
             },
             'actions': [
                 {'merge_yaml': '{foo}.yml'},
             ]
         },
         {
             'pattern': 'all',
             'actions': [
                 {'merge_yaml': 'extra.yml'},
             ]
         }
     ]
     dumper = RuleBasedFileDumper(tmpdir.path, rules)
     dumper.dumpObject({
         'foo': 'thefoo',
     })
     self.assertTrue(tmpdir.child('thefoo.yml').exists(),
         "Should have matched and acted on the first rule")
     dumper.dumpObject({
         'bar': 'hey',
     })
     self.assertTrue(tmpdir.child('extra.yml').exists(),
         "Should have matched and acted on the second rule")
     self.assertEqual(len(tmpdir.children()), 2, "Should only have made "
         "the 2 expected files")
开发者ID:iffy,项目名称:ppd,代码行数:36,代码来源:test_util.py

示例6: doIt

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def doIt(self, txn):


        if raw_input("Do you really want to remove all data [y/n]: ")[0].lower() != 'y':
            print "No data removed"
            returnValue(None)

        wipeout = (
            # These are ordered in such a way as to ensure key constraints are not 
            # violated as data is removed

            schema.RESOURCE_PROPERTY,

            schema.CALENDAR_OBJECT_REVISIONS,

            schema.CALENDAR,
            #schema.CALENDAR_BIND, - cascades
            #schema.CALENDAR_OBJECT, - cascades
            #schema.TIME_RANGE, - cascades
            #schema.TRANSPARENCY, - cascades


            schema.CALENDAR_HOME,
            #schema.CALENDAR_HOME_METADATA - cascades
            schema.ATTACHMENT,

            schema.ADDRESSBOOK_OBJECT_REVISIONS,

            schema.ADDRESSBOOK,
            #schema.ADDRESSBOOK_BIND, - cascades
            #schema.ADDRESSBOOK_OBJECT, - cascades

            schema.ADDRESSBOOK_HOME,
            #schema.ADDRESSBOOK_HOME_METADATA, - cascades

            schema.NOTIFICATION_HOME,
            schema.NOTIFICATION,
            #schema.NOTIFICATION_OBJECT_REVISIONS - cascades,
        )

        for tableschema in wipeout:
            yield self.removeTableData(txn, tableschema)
            print "Removed rows in table %s" % (tableschema,)

        if calendaruserproxy.ProxyDBService is not None:
            calendaruserproxy.ProxyDBService.clean() #@UndefinedVariable
            print "Removed all proxies"
        else:
            print "No proxy database to clean."

        fp = FilePath(config.AttachmentsRoot)
        if fp.exists():
            for child in fp.children():
                child.remove()
            print "Removed attachments."
        else:
            print "No attachments path to delete."
开发者ID:azbarcea,项目名称:calendarserver,代码行数:59,代码来源:dbinspect.py

示例7: TestOpenSSHConfig

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
class TestOpenSSHConfig(unittest.TestCase):

    def setUp(self):
        self.directory = FilePath(self.mktemp())
        self.directory.createDirectory()

    def test_files(self):
        openSSHConfig.setupConfig(self.directory.path, 2222)
        for file in self.directory.children():
            f = file.open()
            contents = f.read()
            f.close()
            self.assertTrue("%" not in contents)
        self.assertEquals(len(self.directory.children()), 5)

    def test_commandOptions(self):
        for option in openSSHConfig.setupConfig(self.directory.path, 2222):
            self.assertTrue("%" not in option)
开发者ID:alex,项目名称:ess,代码行数:20,代码来源:test_openSSHConfig.py

示例8: test_unpartialize

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
 def test_unpartialize(self):
     xpg = self.xpg_with_backup_dir()
     folder = FilePath(xpg.archive_log_directory)
     folder.child("1").touch()
     folder.child("2").touch()
     folder.child("3").touch()
     folder.child("4.partial").touch()
     xpg.unpartialize()
     self.assertEquals(set([c.basename() for c in folder.children()]),
                       set(['1', '2', '3', '4']))
开发者ID:unofficial-opensource-apple,项目名称:PostgreSQL,代码行数:12,代码来源:test_xpostgres.py

示例9: loadServices

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
def loadServices(base):
    from braid import config

    services = {}
    servicesDir = FilePath(base).sibling('services')
    for serviceDir in servicesDir.children():
        serviceName = serviceDir.basename()
        fabfile = serviceDir.child('fabfile.py')
        if fabfile.exists():
            module = imp.load_source(serviceName, fabfile.path, fabfile.open())
            if module.config == config:
                del module.config
            services[serviceName] = module
    return services
开发者ID:OpenSorceress,项目名称:braid,代码行数:16,代码来源:utils.py

示例10: assertExtractedStructure

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def assertExtractedStructure(self, outputFile, dirDict):
        """
        Assert that a tarfile content is equivalent to one described by a dict.

        @param outputFile: The tar file built by L{DistributionBuilder}.
        @type outputFile: L{FilePath}.
        @param dirDict: The dict that should describe the contents of the
            directory. It should be the same structure as the C{dirDict}
            parameter to L{createStructure}.
        @type dirDict: C{dict}
        """
        tarFile = tarfile.TarFile.open(outputFile.path, "r:bz2")
        extracted = FilePath(self.mktemp())
        extracted.createDirectory()
        for info in tarFile:
            tarFile.extract(info, path=extracted.path)
        self.assertStructure(extracted.children()[0], dirDict)
开发者ID:exarkun,项目名称:newsbuilder,代码行数:19,代码来源:test_newsbuilder.py

示例11: test_log_pruning

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def test_log_pruning(self):
        """
        L{XPostgres.prune_useless_archive_logs} will remove unhelpful log
        files.
        """
        xpg = self.xpg_with_backup_dir()
        folder = FilePath(xpg.archive_log_directory)
        folder.child("base_backup").createDirectory()
        folder.child("unknown").touch()
        folder.child("foo.bar.partial").touch()
        folder.child("foo.bar").touch()
        (folder.child("something").temporarySibling(".in-progress")
         .open().close())

        xpg.prune_useless_archive_logs()
        self.assertEquals(set([c.basename() for c in folder.children()]),
                          set(['base_backup', 'unknown', 'foo.bar']))
开发者ID:unofficial-opensource-apple,项目名称:PostgreSQL,代码行数:19,代码来源:test_xpostgres.py

示例12: test_add_node

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
 def test_add_node(self):
     """
     ``Certificates.add_node`` generates another node certificate.
     """
     output = FilePath(self.mktemp())
     output.makedirs()
     certificates = Certificates.generate(output, b"some-service", 2,
                                          b"test-cluster")
     certificates.add_node(3)
     self.assertEqual(
         {
             output.child(b"cluster.crt"), output.child(b"cluster.key"),
             output.child(b"control-some-service.crt"),
             output.child(b"control-some-service.key"),
             output.child(b"user.crt"), output.child(b"user.key"),
             output.child(b"node-0.crt"), output.child(b"node-0.key"),
             output.child(b"node-1.crt"), output.child(b"node-1.key"),
             output.child(b"node-3.crt"), output.child(b"node-3.key"),
         },
         set(output.children()),
     )
开发者ID:332054781,项目名称:flocker,代码行数:23,代码来源:test_ca.py

示例13: test_generated

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
    def test_generated(self):
        """
        ``Certificates.generate`` generates a certificate authority
        certificate, a control service certificate, a user certificate, and the
        given number of node certificates.
        """
        output = FilePath(self.mktemp())
        output.makedirs()
        Certificates.generate(output, b"some-service", 2, b"test-cluster")

        self.assertEqual(
            {
                output.child(b"cluster.crt"), output.child(b"cluster.key"),
                output.child(b"control-some-service.crt"),
                output.child(b"control-some-service.key"),
                output.child(b"user.crt"), output.child(b"user.key"),
                output.child(b"node-0.crt"), output.child(b"node-0.key"),
                output.child(b"node-1.crt"), output.child(b"node-1.key"),
            },
            set(output.children()),
        )
开发者ID:332054781,项目名称:flocker,代码行数:23,代码来源:test_ca.py

示例14: Voluminous

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
class Voluminous(object):
    lockFactory = DockerLock

    def __init__(self, directory):
        self._directory = FilePath(directory)
        self._output = []
        self.lock = self.lockFactory()
        self.commitDatabase = JsonCommitDatabase(self._directory)

    def output(self, s):
        self._output.append(s)
        print s

    def getOutput(self):
        return self._output

    def allBranches(self, volume):
        volumePath = self._directory.child(volume)
        branches = volumePath.child("branches").children()
        return [b.basename() for b in branches if b.isdir()]

    def listBranches(self):
        volume = self.volume()
        branches = self.allBranches(volume)
        currentBranch = self.getActiveBranch(volume)
        self.output("\n".join(sorted(("*" if b == currentBranch else " ") + " " + b for b in branches)))

    def checkoutBranch(self, branch, create):
        """
        "Check out" a branch, restarting containers in process, creating it
        from current branch HEAD if requested.
        """
        volume = self.volume()
        volumePath = self._directory.child(volume)
        # this raises an exception if branch is not a valid path segment
        branchPath = volumePath.child("branches").child(branch)
        if create:
            if branchPath.exists():
                self.output("Cannot create existing branch %s" % (branch,))
                return
            else:
                try:
                    HEAD = self._resolveNamedCommitCurrentBranch("HEAD", volume)
                except IndexError:
                    self.output("You must commit ('dvol commit') before you can " "branch ('dvol checkout -b')")
                    return
                # Copy metadata
                meta = self.commitDatabase.read(volume, self.getActiveBranch(volume))
                self.commitDatabase.write(volume, branch, meta)
                # Then copy latest HEAD of branch into new branch data
                # directory
                copyTo(volumePath.child("commits").child(HEAD), branchPath)
        else:
            if not branchPath.exists():
                self.output("Cannot switch to non-existing branch %s" % (branch,))
                return
        # Got here, so switch to the (maybe new branch)
        self.setActiveBranch(volume, branch)

    def createBranch(self, volume, branch):
        branchDir = self._directory.child(volume).child("branches").child(branch)
        branchDir.makedirs()
        # This branchDir is the one which will be bind-mounted into running
        # containers, via a symlink, but with symlinks and docker bind-mounts
        # it seems that it's the permissions of the target which affects the
        # (e.g.) writeability of the resulting mount.
        # Because some containers have processes which run as non-root users,
        # make the volume world-writeable so that it can still be useful to
        # those processes. In the future, it might be better to have options
        # for which uid, gid and perms the volume should have. This is
        # effectively the same as `chmod a=rwx branchDir.path`.
        os.chmod(branchDir.path, 0777)
        self.output("Created branch %s/%s" % (volume, branch))

    def createVolume(self, name):
        if self._directory.child(name).exists():
            self.output("Error: volume %s already exists" % (name,))
            raise VolumeAlreadyExists()
        self._directory.child(name).makedirs()
        self.setActiveVolume(name)
        self.output("Created volume %s" % (name,))
        self.createBranch(name, DEFAULT_BRANCH)

    def removeVolume(self, volume):
        if not self._directory.child(volume).exists():
            raise UsageError("Volume %r does not exist, cannot remove it" % (volume,))
        containers = self.lock.containers.get_related_containers(volume)
        if containers:
            raise UsageError(
                "Cannot remove %r while it is in use by '%s'" % (volume, (",".join(c["Name"] for c in containers)))
            )
        if self._userIsSure("This will remove all containers using the volume"):
            self.output("Deleting volume %r" % (volume,))
            # Remove related containers
            self.lock.containers.remove_related_containers(volume)
            self._directory.child(volume).remove()

        else:
            self.output("Aborting.")

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

示例15: process_fds

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import children [as 别名]
 def process_fds():
     path = FilePath(b"/proc/self/fd")
     return set([child.basename() for child in path.children()])
开发者ID:hanwoody,项目名称:flocker,代码行数:5,代码来源:__init__.py


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