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


Python FilePath.exists方法代码示例

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


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

示例1: create_credentials

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def create_credentials():
        """
        Create PKI credentials for TLS access to libvirtd.

        Credentials are not signed by the host CA. This only allows
        unverified access but removes the need to transfer files
        between the host and the guest.
        """
        path = FilePath(tempfile.mkdtemp())
        try:
            ca = RootCredential.initialize(path, b"mycluster")
            NodeCredential.initialize(path, ca, uuid='client')
            ca_dir = FilePath('/etc/pki/CA')
            if not ca_dir.exists():
                ca_dir.makedirs()
            path.child(AUTHORITY_CERTIFICATE_FILENAME).copyTo(
                FilePath('/etc/pki/CA/cacert.pem')
            )
            client_key_dir = FilePath('/etc/pki/libvirt/private')
            if not client_key_dir.exists():
                client_key_dir.makedirs()
            client_key_dir.chmod(0700)
            path.child('client.key').copyTo(
                client_key_dir.child('clientkey.pem')
            )
            path.child('client.crt').copyTo(
                FilePath('/etc/pki/libvirt/clientcert.pem')
            )
        finally:
            path.remove()
开发者ID:agonzalezro,项目名称:flocker,代码行数:32,代码来源:test_cinder.py

示例2: parseArgs

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def parseArgs(self, deployment_config, application_config):
        deployment_config = FilePath(deployment_config)
        application_config = FilePath(application_config)

        if not deployment_config.exists():
            raise UsageError('No file exists at {path}'
                             .format(path=deployment_config.path))

        if not application_config.exists():
            raise UsageError('No file exists at {path}'
                             .format(path=application_config.path))

        self["deployment_config"] = deployment_config.getContent()
        self["application_config"] = application_config.getContent()

        try:
            deploy_config_obj = safe_load(self["deployment_config"])
        except YAMLError as e:
            raise UsageError(
                ("Deployment configuration at {path} could not be parsed as "
                 "YAML:\n\n{error}").format(
                    path=deployment_config.path,
                    error=str(e)
                )
            )
        try:
            app_config_obj = safe_load(self["application_config"])
        except YAMLError as e:
            raise UsageError(
                ("Application configuration at {path} could not be parsed as "
                 "YAML:\n\n{error}").format(
                    path=application_config.path,
                    error=str(e)
                )
            )

        try:
            fig_configuration = FigConfiguration(app_config_obj)
            if fig_configuration.is_valid_format():
                applications = fig_configuration.applications()
                self['application_config'] = (
                    applications_to_flocker_yaml(applications)
                )
            else:
                configuration = FlockerConfiguration(app_config_obj)
                if configuration.is_valid_format():
                    applications = configuration.applications()
                else:
                    raise ConfigurationError(
                        "Configuration is not a valid Fig or Flocker format."
                    )
            self['deployment'] = model_from_configuration(
                applications=applications,
                deployment_configuration=deploy_config_obj)
        except ConfigurationError as e:
            raise UsageError(str(e))
开发者ID:LaOnda,项目名称:flocker,代码行数:58,代码来源:script.py

示例3: test_nonexistentPaths

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def test_nonexistentPaths(self):
        """
        Verify that L{modules.walkModules} ignores entries in sys.path which
        do not exist in the filesystem.
        """
        existentPath = FilePath(self.mktemp())
        os.makedirs(existentPath.child("test_package").path)
        existentPath.child("test_package").child("__init__.py").setContent("")

        nonexistentPath = FilePath(self.mktemp())
        self.failIf(nonexistentPath.exists())

        originalSearchPaths = sys.path[:]
        sys.path[:] = [existentPath.path]
        try:
            expected = [modules.getModule("test_package")]

            beforeModules = list(modules.walkModules())
            sys.path.append(nonexistentPath.path)
            afterModules = list(modules.walkModules())
        finally:
            sys.path[:] = originalSearchPaths

        self.assertEqual(beforeModules, expected)
        self.assertEqual(afterModules, expected)
开发者ID:Almad,项目名称:twisted,代码行数:27,代码来源:test_modules.py

示例4: load_revokations

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
 def load_revokations(self):
     """
     Load PEM formatted certificates that are no longer trustworthy
     and store the suject and issuer.
     `cert_list` is the path to a file that contains glob-like patterns
     to PEM-formatted certificates.
     """
     revoke_file = self.revoke_file
     revoke_state = self.revoke_state 
     if revoke_file is not None:
         last_mod_time = revoke_state['last_mod_time']
         fp = FilePath(revoke_file)
         if not fp.exists():
             return
         mod_time = fp.getModificationTime()
         if last_mod_time is None or mod_time > last_mod_time:
             log.msg("[INFO] Loading revoked certificate files specified in '{0}'.".format(
                 revoke_file))
             revoke_state['last_mod_time'] = mod_time
             revoked = set([])
             with open(revoke_file) as f:
                 for line in f:
                     pattern = line.rstrip('\r\n')
                     if pattern == '' or pattern.startswith('#'):
                         continue
                     for path in glob.glob(pattern):
                         certs = [pem_cert_to_x509(cert)
                             for cert in pem.parse_file(path)]
                         for certificate in certs:
                             revoked.add((
                                 tuple(certificate.get_subject().get_components()),
                                 tuple(certificate.get_issuer().get_components())))
             revoke_state['revoked'] = revoked
开发者ID:cwaldbieser,项目名称:txcas,代码行数:35,代码来源:tls_endpoint_parser.py

示例5: activate

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
 def activate(self):
     super(StarboundConfigManager, self).activate()
     try:
         configuration_file = FilePath(
             self.config.starbound_path
         ).child('starbound.config')
         if not configuration_file.exists():
             raise FatalPluginError(
                 'Could not open starbound configuration file. '
                 'Tried path: {}'.format(configuration_file)
             )
     except AttributeError:
         raise FatalPluginError(
             'The starbound path (starbound_path)'
             ' is not set in the configuration.'
         )
     try:
         with configuration_file.open() as f:
             starbound_config = json.load(f)
     except Exception as e:
         raise FatalPluginError(
             'Could not parse the starbound configuration file as JSON.'
             'Error given from JSON decoder: {}'.format(e)
         )
     if self.config.upstream_port != starbound_config['gameServerPort']:
         raise FatalPluginError(
             'The starbound gameServerPort option ({}) does not match the '
             'config.json upstream_port ({}).'.format(
                 starbound_config['gameServerPort'],
                 self.config.upstream_port
             )
         )
开发者ID:GermaniumSystem,项目名称:StarryPy,代码行数:34,代码来源:starbound_config_manager.py

示例6: fromConfig

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def fromConfig(cls, reactor):
        keys = []
        if "identity" in _CONFIG:
            keyPath = os.path.expanduser(_CONFIG["identity"])
            if os.path.exists(keyPath):
                keys.append(readKey(keyPath))

        knownHostsPath = FilePath(os.path.expanduser(_CONFIG["knownhosts"]))
        if knownHostsPath.exists():
            knownHosts = KnownHostsFile.fromPath(knownHostsPath)
        else:
            knownHosts = None

        if "no-agent" in _CONFIG or "SSH_AUTH_SOCK" not in os.environ:
            agentEndpoint = None
        else:
            agentEndpoint = UNIXClientEndpoint(
                reactor, os.environ["SSH_AUTH_SOCK"])

        if "password" in _CONFIG:
            password = _CONFIG["password"]
        else:
            password = None

        return cls(
            reactor, _CONFIG["host"], _CONFIG["port"],
            _CONFIG["username"], password, keys,
            knownHosts, agentEndpoint)
开发者ID:fredericlepied,项目名称:zgerrit,代码行数:30,代码来源:zgerrit.py

示例7: get_device_path

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def get_device_path(self, blockdevice_id):
        # libvirt does not return the correct device path when additional
        # disks have been attached using a client other than cinder. This is
        # expected behaviour within Cinder and libvirt
        # See https://bugs.launchpad.net/cinder/+bug/1387945 and
        # http://libvirt.org/formatdomain.html#elementsDisks (target section)
        # However, the correct device is named as a udev symlink which includes
        # the first 20 characters of the blockedevice_id.
        device_path = FilePath(
            "/dev/disk/by-id/virtio-{}".format(blockdevice_id[:20]))
        if not device_path.exists():
            # If the device path does not exist, either virtio driver is
            # not being used (e.g. Rackspace), or the user has modified
            # their udev rules.  The following code relies on Cinder
            # returning the correct device path, which appears to work
            # for Rackspace and will work with virtio if no disks have
            # been attached outside Cinder.
            try:
                cinder_volume = self.cinder_volume_manager.get(blockdevice_id)
            except CinderNotFound:
                raise UnknownVolume(blockdevice_id)

            # As far as we know you can not have more than one attachment,
            # but, perhaps we're wrong and there should be a test for the
            # multiple attachment case.  FLOC-1854.
            try:
                [attachment] = cinder_volume.attachments
            except ValueError:
                raise UnattachedVolume(blockdevice_id)

            device_path = FilePath(attachment['device'])

        # It could be attached somewhere else...
        # https://clusterhq.atlassian.net/browse/FLOC-1830
        return device_path
开发者ID:agonzalezro,项目名称:flocker,代码行数:37,代码来源:cinder.py

示例8: copyPackage

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def copyPackage(title):
        """
        Copy package directory to db path using a file lock to avoid potential
        concurrency race conditions.

        @param title: string to use in log entry
        @type title: C{str}
        """
        dbpath = FilePath(TimezoneCache.getDBPath())
        pkgpath = TimezoneCache.FilteredFilePath(TimezoneCache._getPackageDBPath())

        lockfile = FilesystemLock(dbpath.path + ".lock")
        result = lockfile.lock()
        try:
            if result and not dbpath.exists():
                log.info(
                    "{title} timezones from {pkg} to {to}",
                    title=title,
                    pkg=pkgpath.path,
                    to=dbpath.path
                )

                # Copy over the entire package
                pkgpath.copyFilteredDirectoryTo(dbpath)
        finally:
            if result:
                lockfile.unlock()
开发者ID:red-hood,项目名称:calendarserver,代码行数:29,代码来源:timezones.py

示例9: getTemplate

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def getTemplate(self, facetName):
        templatePath = FilePath(
            self.node.__file__
            ).sibling(facetName + ".mak")

        if templatePath.exists():
            return templatePath
开发者ID:bhomnick,项目名称:warp,代码行数:9,代码来源:resource.py

示例10: inspect

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
def inspect(doc):
    data = json.loads(doc)
    path = FilePath(data['path'])
    ret = {'kind': 'file', 'path': path.path, 'exists': path.exists()}
    if not ret['exists']:
        return ret
    
    if path.isdir():
        ret['filetype'] = 'dir'
    elif path.isfile():
        ret['filetype'] = 'file'
        ret['size'] = path.statinfo.st_size
        h = sha1()
        fh = open(path.path, 'r')
        while True:
            data = fh.read(4096)
            if not data:
                break
            h.update(data)
        ret['sha1'] = h.hexdigest()

    ret['owner'] = pwd.getpwuid(path.getUserID()).pw_name
    ret['group'] = grp.getgrgid(path.getGroupID()).gr_name
    ret['perms'] = permsString(path.getPermissions())
    ret['ctime'] = int(path.statinfo.st_ctime)
    ret['mtime'] = int(path.statinfo.st_mtime)
    ret['atime'] = int(path.statinfo.st_atime)
    return ret
开发者ID:hagna,项目名称:mold,代码行数:30,代码来源:file.py

示例11: monitoring_check

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
def monitoring_check(checker, lasterrors_path, from_email, what, stdout, stderr):
    error_stream = StringIO()

    lasterrors = None
    lasterrors_fp = FilePath(lasterrors_path)
    if lasterrors_fp.exists():
        lasterrors = lasterrors_fp.getContent()

    d = checker(stdout, error_stream)
    def cb(x):
        if isinstance(x, Failure):
            print >>stderr, str(x)
            if hasattr(x.value, 'response'):
                print >>stderr, x.value.response

        errors = error_stream.getvalue()
        print >>stderr, errors
        if errors != lasterrors:
            d2 = send_monitoring_report(errors, from_email, what)
            def _sent(ign):
                lasterrors_fp.setContent(errors)
                raise Exception("Sent failure report.")
            def _err(f):
                print >>stderr, str(f)
                return f
            d2.addCallbacks(_sent, _err)
            return d2
    d.addBoth(cb)
    return d
开发者ID:pombredanne,项目名称:leastauthority.com,代码行数:31,代码来源:monitor.py

示例12: copyPackage

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def copyPackage(title):
        """
        Copy package directory to db path using a temporary sibling to avoid potential
        concurrency race conditions.

        @param title: string to use in log entry
        @type title: C{str}
        """
        dbpath = FilePath(TimezoneCache.getDBPath())
        pkgpath = TimezoneCache.FilteredFilePath(TimezoneCache._getPackageDBPath())
        log.info(
            "{title} timezones from {pkg} to {to}",
            title=title,
            pkg=pkgpath.path,
            to=dbpath.path
        )

        # Use temp directory to copy to first
        temp = dbpath.temporarySibling()
        pkgpath.copyFilteredDirectoryTo(temp)

        # Move to actual path if it stll does not exist
        if not dbpath.exists():
            temp.moveTo(dbpath)
        else:
            temp.remove()
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:28,代码来源:timezones.py

示例13: _check_cert_directory

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
 def _check_cert_directory(self):
     cert_path = FilePath(self['cert-directory'])
     self['cert-directory'] = cert_path
     if not cert_path.exists():
         raise UsageError("{} does not exist".format(cert_path.path))
     if not cert_path.isdir():
         raise UsageError("{} is not a directory".format(cert_path.path))
开发者ID:332054781,项目名称:flocker,代码行数:9,代码来源:cluster_add_nodes.py

示例14: test_create

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def test_create(self):
        """
        You can create a directory from a template
        """
        t_root = FilePath(self.mktemp())
        t_root.makedirs()
        
        d1 = t_root.child('dir1')
        d1.makedirs()
        f1 = d1.child('foo')
        f1.setContent('foo content')
        d2 = d1.child('dir2')
        d2.makedirs()
        f2 = d2.child('bar')
        f2.setContent('bar content')

        dst = FilePath(self.mktemp())
        d = Directory(dst.path)
        # fake template root
        d.template_root = t_root
        
        d.create('dir1')
        self.assertTrue(dst.exists())
        self.assertEqual(dst.child('foo').getContent(), 'foo content')
        self.assertTrue(dst.child('dir2').exists())
        self.assertEqual(dst.child('dir2').child('bar').getContent(),
                         'bar content')
开发者ID:hagna,项目名称:mold,代码行数:29,代码来源:test_install.py

示例15: _get_device_path_virtio_blk

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import exists [as 别名]
    def _get_device_path_virtio_blk(self, volume):
        """
        The virtio_blk driver allows a serial number to be assigned to virtual
        blockdevices.
        OpenStack will set a serial number containing the first 20
        characters of the Cinder block device ID.

        This was introduced in
        * https://github.com/openstack/nova/commit/3a47c02c58cefed0e230190b4bcef14527c82709  # noqa
        * https://bugs.launchpad.net/nova/+bug/1004328

        The udev daemon will read the serial number and create a
        symlink to the canonical virtio_blk device path.

        We do this because libvirt does not return the correct device path when
        additional disks have been attached using a client other than
        cinder. This is expected behaviour within Cinder and libvirt See
        https://bugs.launchpad.net/cinder/+bug/1387945 and
        http://libvirt.org/formatdomain.html#elementsDisks (target section)

        :param volume: The Cinder ``Volume`` which is attached.
        :returns: ``FilePath`` of the device created by the virtio_blk
            driver.
        """
        expected_path = FilePath(
            "/dev/disk/by-id/virtio-{}".format(volume.id[:20])
        )
        if expected_path.exists():
            return expected_path.realpath()
        else:
            raise UnattachedVolume(volume.id)
开发者ID:justinclayton,项目名称:flocker,代码行数:33,代码来源:cinder.py


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