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


Python FilePath.isdir方法代码示例

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


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

示例1: inspect

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [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

示例2: _check_cert_directory

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [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

示例3: test_directory_is_created

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
 def test_directory_is_created(self):
     """
     If a directory does not exist in given path, it is created.
     """
     path = FilePath(self.mktemp())
     self.service(path)
     self.assertTrue(path.isdir())
开发者ID:332054781,项目名称:flocker,代码行数:9,代码来源:test_persistence.py

示例4: test_starts_persistence_service

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
 def test_starts_persistence_service(self):
     """
     ``ControlScript.main`` starts a configuration persistence service.
     """
     path = FilePath(self.mktemp())
     options = ControlOptions()
     options.parseOptions([b"--data-path", path.path])
     reactor = MemoryCoreReactor()
     ControlScript().main(reactor, options)
     self.assertTrue(path.isdir())
开发者ID:ALSEDLAH,项目名称:flocker,代码行数:12,代码来源:test_script.py

示例5: gotStatus

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
 def gotStatus(status):
     extraDiffs = []
     lines = status.splitlines()
     for L in lines:
         if L.startswith('A'):
             ignored, ignored, fileName = L.split(None, 2)
             path = FilePath(self.projectTrunk).preauthChild(fileName)
             if not path.isdir():
                 extraDiffs.append(
                     getProcessOutput(
                         "diff", ("-u", "/dev/null", path.path), env=environ))
     return gatherResults(extraDiffs)
开发者ID:twisted-infra,项目名称:diffresource,代码行数:14,代码来源:diffresource.py

示例6: ControlScriptTests

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
class ControlScriptTests(TestCase):
    """
    Tests for ``ControlScript``.
    """
    def setUp(self):
        """
        Create some certificates to use when creating the control service.
        """
        super(ControlScriptTests, self).setUp()
        ca_set, _ = get_credential_sets()
        self.certificate_path = FilePath(self.mktemp())
        self.certificate_path.makedirs()
        ca_set.copy_to(self.certificate_path, control=True)
        self.script = ControlScript()
        self.options = ControlOptions()
        self.data_path = FilePath(self.mktemp())
        self.options.parseOptions([
            b"--port", b"tcp:8001", b"--agent-port", b"tcp:8002",
            b"--data-path", self.data_path.path,
            b"--certificates-directory", self.certificate_path.path
        ])

    def test_no_immediate_stop(self):
        """
        The ``Deferred`` returned from ``ControlScript`` is not fired.
        """
        self.assertNoResult(
            self.script.main(MemoryCoreReactor(), self.options))

    def test_starts_persistence_service(self):
        """
        ``ControlScript.main`` starts a configuration persistence service.
        """
        reactor = MemoryCoreReactor()
        self.script.main(reactor, self.options)
        self.assertTrue(self.data_path.isdir())

    def test_starts_cluster_state_service(self):
        """
        ``ControlScript.main`` starts a cluster state service.
        """
        reactor = MemoryCoreReactor()
        self.script.main(reactor, self.options)
        server = reactor.tcpServers[0]
        control_resource = server[1].wrappedFactory.resource
        service = control_resource._v1_user.cluster_state_service
        self.assertEqual((service.__class__, service.running),
                         (ClusterStateService, True))
开发者ID:332054781,项目名称:flocker,代码行数:50,代码来源:test_script.py

示例7: _find_suite

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
def _find_suite():
    root = os.environ.get("JSON_SCHEMA_TEST_SUITE")
    if root is not None:
        return FilePath(root)

    root = FilePath(jsonschema.__file__).parent().sibling("json")
    if not root.isdir():  # pragma: no cover
        raise ValueError(
            (
                "Can't find the JSON-Schema-Test-Suite directory. "
                "Set the 'JSON_SCHEMA_TEST_SUITE' environment "
                "variable or run the tests from alongside a checkout "
                "of the suite."
            ),
        )
    return root
开发者ID:Julian,项目名称:jsonschema,代码行数:18,代码来源:_suite.py

示例8: walk

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
 def walk(self, path):
     containers = []
     filepath = FilePath(path)
     if filepath.isdir():
         containers.append(filepath)
     elif filepath.isfile():
         self.items.append(FilePath(path))
     while len(containers)>0:
         container = containers.pop()
         try:
             for child in container.children():
                 if child.isdir():
                     containers.append(child)
                 elif child.isfile() or child.islink():
                     mimetype,_ = mimetypes.guess_type(child.path, strict=False)
                     if mimetype and mimetype.startswith("image/"):
                         self.items.append(child)
         except UnicodeDecodeError:
             self.warning("UnicodeDecodeError - there is something wrong with a file located in %r", container.get_path())
开发者ID:BlackHole,项目名称:coherence,代码行数:21,代码来源:base.py

示例9: do_urlextract

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
def do_urlextract(dest, url):
    global dsklst
    dest=FilePath(dest)

    # Don't do this if not mounted!
    mntpnt=dsklst['/'].real_mountpoint()
    if not os.path.ismount(mntpnt):
        return False

    if not dest.isdir():
        return False
   
    try:
        uh=urllib2.urlopen(url)
        tf=tarfile.open(mode='r|*',fileobj=uh)
        os.chroot(mntpnt)
        os.chdir(os.path.join(dest.dirname(),dest.basename()))
        tf.extractall()
    except:
        traceback.print_exc()
    os.chdir('/')
开发者ID:ewindisch,项目名称:nodestored,代码行数:23,代码来源:nodestored.py

示例10: getDirectory

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
    def getDirectory(self, path='/'):

        self.fs = yield FilePath(path)

        if not self.fs.getPermissions():
            defer.returnValue(False)

        files = []

        for f in self.fs.listdir():
            if f == '/':
                continue

            fp = path+f
            fs = FilePath(fp)

            # dont follow symlinks
            if fs.realpath().path != fp:
                continue

            perm = None
            isdir = fs.isdir()
            size = fs.getsize()
            modified = datetime.utcfromtimestamp(fs.getModificationTime())

            df = DiscoveredFile(
                resource_id=self.data['resource_id'],
                file_path=path,
                file_name=f,
                file_isdir=isdir,
                file_size=size,
                file_modified=modified,
                file_perm=perm
            )

            print '[%s] LIST %s.' % (self.data['resource_name'], fp if not fp.endswith('.') else fp)
            files.append(df)

        defer.returnValue(files)
开发者ID:pombredanne,项目名称:findex-crawl,代码行数:41,代码来源:filesystem.py

示例11: logsCoerce

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
def logsCoerce(directory):
    path = FilePath(directory)
    if not path.isdir():
        raise ValueError("%r is not a directory" % (path.path,))
    return path
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:7,代码来源:benchmark.py

示例12: DropUploader

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
class DropUploader(service.MultiService):
    name = 'drop-upload'

    def __init__(self, client, upload_dircap, local_dir_utf8, inotify=None):
        service.MultiService.__init__(self)

        try:
            local_dir_u = abspath_expanduser_unicode(local_dir_utf8.decode('utf-8'))
            if sys.platform == "win32":
                local_dir = local_dir_u
            else:
                local_dir = local_dir_u.encode(get_filesystem_encoding())
        except (UnicodeEncodeError, UnicodeDecodeError):
            raise AssertionError("The '[drop_upload] local.directory' parameter %s was not valid UTF-8 or "
                                 "could not be represented in the filesystem encoding."
                                 % quote_output(local_dir_utf8))

        self._client = client
        self._stats_provider = client.stats_provider
        self._convergence = client.convergence
        self._local_path = FilePath(local_dir)

        if inotify is None:
            from twisted.internet import inotify
        self._inotify = inotify

        if not self._local_path.exists():
            raise AssertionError("The '[drop_upload] local.directory' parameter was %s but there is no directory at that location." % quote_output(local_dir_u))
        if not self._local_path.isdir():
            raise AssertionError("The '[drop_upload] local.directory' parameter was %s but the thing at that location is not a directory." % quote_output(local_dir_u))

        # TODO: allow a path rather than a cap URI.
        self._parent = self._client.create_node_from_uri(upload_dircap)
        if not IDirectoryNode.providedBy(self._parent):
            raise AssertionError("The '[drop_upload] upload.dircap' parameter does not refer to a directory.")
        if self._parent.is_unknown() or self._parent.is_readonly():
            raise AssertionError("The '[drop_upload] upload.dircap' parameter is not a writecap to a directory.")

        self._uploaded_callback = lambda ign: None

        self._notifier = inotify.INotify()

        # We don't watch for IN_CREATE, because that would cause us to read and upload a
        # possibly-incomplete file before the application has closed it. There should always
        # be an IN_CLOSE_WRITE after an IN_CREATE (I think).
        # TODO: what about IN_MOVE_SELF or IN_UNMOUNT?
        mask = inotify.IN_CLOSE_WRITE | inotify.IN_MOVED_TO | inotify.IN_ONLYDIR
        self._notifier.watch(self._local_path, mask=mask, callbacks=[self._notify])

    def startService(self):
        service.MultiService.startService(self)
        d = self._notifier.startReading()
        self._stats_provider.count('drop_upload.dirs_monitored', 1)
        return d

    def _notify(self, opaque, path, events_mask):
        self._log("inotify event %r, %r, %r\n" % (opaque, path, ', '.join(self._inotify.humanReadableMask(events_mask))))

        self._stats_provider.count('drop_upload.files_queued', 1)
        eventually(self._process, opaque, path, events_mask)

    def _process(self, opaque, path, events_mask):
        d = defer.succeed(None)

        # FIXME: if this already exists as a mutable file, we replace the directory entry,
        # but we should probably modify the file (as the SFTP frontend does).
        def _add_file(ign):
            name = path.basename()
            # on Windows the name is already Unicode
            if not isinstance(name, unicode):
                name = name.decode(get_filesystem_encoding())

            u = FileName(path.path, self._convergence)
            return self._parent.add_file(name, u)
        d.addCallback(_add_file)

        def _succeeded(ign):
            self._stats_provider.count('drop_upload.files_queued', -1)
            self._stats_provider.count('drop_upload.files_uploaded', 1)
        def _failed(f):
            self._stats_provider.count('drop_upload.files_queued', -1)
            if path.exists():
                self._log("drop-upload: %r failed to upload due to %r" % (path.path, f))
                self._stats_provider.count('drop_upload.files_failed', 1)
                return f
            else:
                self._log("drop-upload: notified file %r disappeared "
                          "(this is normal for temporary files): %r" % (path.path, f))
                self._stats_provider.count('drop_upload.files_disappeared', 1)
                return None
        d.addCallbacks(_succeeded, _failed)
        d.addBoth(self._uploaded_callback)
        return d

    def set_uploaded_callback(self, callback):
        """This sets a function that will be called after a file has been uploaded."""
        self._uploaded_callback = callback

    def finish(self, for_tests=False):
        self._notifier.stopReading()
#.........这里部分代码省略.........
开发者ID:WinLAFS,项目名称:tahoe-lafs,代码行数:103,代码来源:drop_upload.py

示例13: __init__

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
class DirDBM:
    """
    A directory with a DBM interface.

    This class presents a hash-like interface to a directory of small,
    flat files. It can only use strings as keys or values.
    """

    def __init__(self, name):
        """
        @type name: str
        @param name: Base path to use for the directory storage.
        """
        self.dname = os.path.abspath(name)
        self._dnamePath = FilePath(name)
        if not self._dnamePath.isdir():
            self._dnamePath.createDirectory()
        else:
            # Run recovery, in case we crashed. we delete all files ending
            # with ".new". Then we find all files who end with ".rpl". If a
            # corresponding file exists without ".rpl", we assume the write
            # failed and delete the ".rpl" file. If only a ".rpl" exist we
            # assume the program crashed right after deleting the old entry
            # but before renaming the replacement entry.
            #
            # NOTE: '.' is NOT in the base64 alphabet!
            for f in glob.glob(self._dnamePath.child("*.new").path):
                os.remove(f)
            replacements = glob.glob(self._dnamePath.child("*.rpl").path)
            for f in replacements:
                old = f[:-4]
                if os.path.exists(old):
                    os.remove(f)
                else:
                    os.rename(f, old)


    def _encode(self, k):
        """
        Encode a key so it can be used as a filename.
        """
        # NOTE: '_' is NOT in the base64 alphabet!
        return base64.encodestring(k).replace(b'\n', b'_').replace(b"/", b"-")


    def _decode(self, k):
        """
        Decode a filename to get the key.
        """
        return base64.decodestring(k.replace(b'_', b'\n').replace(b"-", b"/"))


    def _readFile(self, path):
        """
        Read in the contents of a file.

        Override in subclasses to e.g. provide transparently encrypted dirdbm.
        """
        with _open(path.path, "rb") as f:
            s = f.read()
        return s


    def _writeFile(self, path, data):
        """
        Write data to a file.

        Override in subclasses to e.g. provide transparently encrypted dirdbm.
        """
        with _open(path.path, "wb") as f:
            f.write(data)
            f.flush()


    def __len__(self):
        """
        @return: The number of key/value pairs in this Shelf
        """
        return len(self._dnamePath.listdir())


    def __setitem__(self, k, v):
        """
        C{dirdbm[k] = v}
        Create or modify a textfile in this directory

        @type k: bytes
        @param k: key to set

        @type v: bytes
        @param v: value to associate with C{k}
        """
        if not type(k) == bytes:
            raise TypeError("DirDBM key must be bytes")
        if not type(v) == bytes:
            raise TypeError("DirDBM value must be bytes")
        k = self._encode(k)

        # We create a new file with extension .new, write the data to it, and
        # if the write succeeds delete the old file and rename the new one.
#.........这里部分代码省略.........
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:103,代码来源:dirdbm.py

示例14: FSItem

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
class FSItem(BackendItem):
    logCategory = 'fs_item'

    def __init__(self, object_id, parent, path, mimetype, urlbase, UPnPClass,update=False):
        self.id = object_id
        self.parent = parent
        if parent:
            parent.add_child(self,update=update)
        if mimetype == 'root':
            self.location = unicode(path)
        else:
            if mimetype == 'item' and path is None:
                path = os.path.join(parent.get_path(),unicode(self.id))
            #self.location = FilePath(unicode(path))
            self.location = FilePath(path)
        self.mimetype = mimetype
        if urlbase[-1] != '/':
            urlbase += '/'
        self.url = urlbase + str(self.id)


        if parent == None:
            parent_id = -1
        else:
            parent_id = parent.get_id()

        self.item = UPnPClass(object_id, parent_id, self.get_name())
        if isinstance(self.item, Container):
            self.item.childCount = 0
        self.child_count = 0
        self.children = []


        if mimetype in ['directory','root']:
            self.update_id = 0
            self.get_url = lambda : self.url
            self.get_path = lambda : None
            #self.item.searchable = True
            #self.item.searchClass = 'object'
            if(isinstance(self.location,FilePath) and
               self.location.isdir() == True):
                self.check_for_cover_art()
                if hasattr(self, 'cover'):
                    _,ext =  os.path.splitext(self.cover)
                    """ add the cover image extension to help clients not reacting on
                        the mimetype """
                    self.item.albumArtURI = ''.join((urlbase,str(self.id),'?cover',ext))
        else:
            self.get_url = lambda : self.url

            if self.mimetype.startswith('audio/'):
                if hasattr(parent, 'cover'):
                    _,ext =  os.path.splitext(parent.cover)
                    """ add the cover image extension to help clients not reacting on
                        the mimetype """
                    self.item.albumArtURI = ''.join((urlbase,str(self.id),'?cover',ext))

            _,host_port,_,_,_ = urlsplit(urlbase)
            if host_port.find(':') != -1:
                host,port = tuple(host_port.split(':'))
            else:
                host = host_port

            try:
                size = self.location.getsize()
            except:
                size = 0

            if mimetype != 'item':
                res = Resource('file://'+ urllib.quote(self.get_path()), 'internal:%s:%s:*' % (host,self.mimetype))
                res.size = size
                self.item.res.append(res)

            if mimetype != 'item':
                res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
            else:
                res = Resource(self.url, 'http-get:*:*:*')

            res.size = size
            self.item.res.append(res)


            """ if this item is an image and we want to add a thumbnail for it
                we have to follow these rules:

                create a new Resource object, at least a 'http-get'
                and maybe an 'internal' one too

                for an JPG this looks like that

                res = Resource(url_for_thumbnail,
                        'http-get:*:image/jpg:%s'% ';'.join(simple_dlna_tags+('DLNA.ORG_PN=JPEG_TN',)))
                res.size = size_of_thumbnail
                self.item.res.append(res)

                and for a PNG the Resource creation is like that

                res = Resource(url_for_thumbnail,
                        'http-get:*:image/png:%s'% ';'.join(simple_dlna_tags+('DLNA.ORG_PN=PNG_TN',)))

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

示例15: DirectoryDeadProperties

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import isdir [as 别名]
class DirectoryDeadProperties(object):
    """
    An implementation of a DeadPropertyStore (i.e. store for persistent properties).
    We store the dead properties in a directory tree _parallel_ to the resource tree.
    The path to a resource's metadata relative to the root of the metadata directory tree
    is the same as the path of the resource content relative to the repository root.
    Every resource's metadata is represented as a directory: every metadata entry is 
    represented as a file pickle in that directory.
    """
    implements(IDeadPropertyStore)
    
    def __init__(self, _resource):
        self.resource = _resource
        self.metadataPath = FilePath(metadata + os.sep + self.resource.relativePath())
        self.__sanitize()
    
    def _fileNameFor(self, qname):
        """
        @return: a file name for a property of this resource
        """
        return self.metadataPath.path + os.sep + qname[1]
    
    def __sanitize(self):
        """
        The problem we're trying to address here (rather than simply putting it into the constructor) 
        is that seemingly, in twisted, an object's method may be called _before_ the constructor has
        returned (if the constructor is doing some non-blocking shizzle, that is).
        So we provide a separate file system sanity check which we call before every call to this
        that hits the file system, to e.g. ensure that the containing directory exists.
        """
        # perform sanity check:
        if os.path.exists(self.metadataPath.path):
            assert self.metadataPath.isdir(), \
                "metadata store must be a directory: " + self.metaDataPath.path
        else:
            log.info("Creating metadata store for: %s", self.metadataPath.path)
            os.mkdir(self.metadataPath.path)
        
    def get(self, qname):
        """
        @param qname (see twisted.web2.dav.davxml) of the property to look for.
        """
        self.__sanitize()
        obj = None
        try:
            obj = cPickle.load(open(self._fileNameFor(qname)))
        except (IOError, EOFError, cPickle.PickleError):
            return None
        return obj

    def set(self, property):
        """
        @param property -- an instance of twisted.web2.dav.davxml.WebDAVElement
        """
        self.__sanitize()
        transaction = SingleFileTransaction()
        try:
            f = transaction.open(self._fileNameFor(property.qname()), 'wb')
            cPickle.dump(property, f)
            f.close()
        except cPickle.PickleError, e:
            transaction.cleanup()
            log.warn("A problem occured while saving property %s:", property.qname(), exc_info = e)
            raise
        else:
开发者ID:infothrill,项目名称:angel-app-svnmirror,代码行数:67,代码来源:DirectoryDeadProperties.py


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