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


Python OSFS.listdir方法代码示例

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


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

示例1: Recent

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
class Recent(Files):
    def __init__(self):
        super(Recent, self).__init__()
        self._paths = []
        # http://python.6.n6.nabble.com/Access-Most-Recently-Used-MRU-entries-td1953541.html
        self.mru_path = shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_RECENT, 0)
        self.mrufs = OSFS(self.mru_path)
        self.watcher = None

    def setup(self):
        self._update_path()
        self.watcher = self.mrufs.add_watcher(lambda e: self._update_path())

    def _update_path(self):
        self._paths = sorted(
            [os.path.join(self.mru_path, f) for f in self.mrufs.listdir()], key=os.path.getmtime, reverse=True
        )
        self.path_list_changed()

    def teardown(self):
        if self.watcher:
            self.mrufs.del_watcher(self.watcher)

    @property
    def paths(self):
        return self._paths

    @property
    def name(self):
        return "re"

    def lit(self, *args, **kargs):
        return super(Recent, self).lit(*args, **kargs)
开发者ID:Answeror,项目名称:lit,代码行数:35,代码来源:recent.py

示例2: cleanup

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
def cleanup(source, destination_temp, standard):
	"""Remove the source and temporary destination folders."""

	try:
		source_fs = OSFS('%s/%s' % (source, standard))
	except ResourceNotFoundError:
		return None

	destination_fs = OSFS(destination_temp)

	artifacts = source_fs.listdir(dirs_only=True)
	if '.git' in artifacts: artifacts.remove('.git')

	for artifact in artifacts:
		path = '%s/%s' % (artifact, standard)
		if destination_fs.exists(path):
			destination_fs.removedir(path, force=True)

	if destination_fs.exists(standard): destination_fs.removedir(standard, force=True)
开发者ID:fterpstra,项目名称:technisch-register,代码行数:21,代码来源:utils.py

示例3: run

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
    def run(self):
        parser = self.get_argparse()
        args = parser.parse_args(sys.argv[1:])

        if args.version is None:
            major, minor = __version__.split('.')[:2]
            version = "{}.{}".format(major, minor)
        else:
            version = args.version

        try:
            with open(expanduser(args.settings), 'rt') as f_ini:
                cfg = SettingsContainer.read_from_file(f_ini)
                print("Read settings from {}".format(args.settings))
        except IOError:
            cfg = SettingsContainer()

        from ..docgen.extracter import Extracter
        from ..docgen.builder import Builder
        from ..command import doc_project
        location = dirname(doc_project.__file__)

        extract_fs = OSFS(join('doccode', version), create=True)
        base_docs_fs = OSFS('text')
        languages = [d for d in base_docs_fs.listdir(dirs_only=True) if len(d) == 2]

        def do_extract():
            print("Extracting docs v{}".format(version))
            utils.remove_all(extract_fs, '/')
            try:
                archive, context, doc = moya_build.build_server(location, 'settings.ini')
            except Exception:
                raise
                return -1

            extract_fs.makedir("site/docs", recursive=True)
            extract_fs.makedir("site/tags", recursive=True)
            #extract_fs.makedir("libs")

            with extract_fs.opendir('site/tags') as tags_fs:
                extracter = Extracter(archive, tags_fs)
                const_data = {}
                builtin_tags = []
                for namespace in self.builtin_namespaces:
                    xmlns = getattr(namespaces, namespace, None)
                    if xmlns is None:
                        raise ValueError("XML namespace '{}' is not in namespaces.py".format(namespace))
                    namespace_tags = archive.registry.get_elements_in_xmlns(xmlns).values()
                    builtin_tags.extend(namespace_tags)

                extracter.extract_tags(builtin_tags, const_data=const_data)

            for language in languages:
                with extract_fs.makeopendir("site/docs") as language_fs:
                    doc_extracter = Extracter(None, language_fs)
                    docs_fs = base_docs_fs.opendir(language)
                    doc_extracter.extract_site_docs(docs_fs, dirname=language)

        if args.extract:
            do_extract()

        if args.build:
            theme_path = cfg.get('paths', 'theme', None)
            dst_path = join('html', version)
            if theme_path is None:
                theme_fs = OSFS('theme')
            else:
                theme_fs = fsopendir(theme_path)

            output_path = cfg.get('paths', 'output', None)

            if output_path is None:
                output_base_fs = OSFS(dst_path, create=True)
            else:
                output_root_base_fs = fsopendir(output_path)
                output_base_fs = output_root_base_fs.makeopendir(dst_path, recursive=True)

            #output_base_fs = OSFS(join('html', version), create=True)
            utils.remove_all(output_base_fs, '/')

            def do_build():
                print("Building docs v{}".format(version))
                lib_info = {}
                lib_paths = {}
                for long_name, lib in self.document_libs:
                    lib_info[long_name] = moya_build.get_lib_info(lib)
                    lib_paths[long_name] = output_base_fs.getsyspath(join('libs', long_name, 'index.html'))
                for language in languages:
                    docs_fs = base_docs_fs.makeopendir(language)
                    output_fs = output_base_fs.makeopendir(language)
                    utils.remove_all(output_fs, '/')

                    with extract_fs.opendir("site") as extract_site_fs:
                        builder = Builder(extract_site_fs, output_fs, theme_fs)
                        from ..tools import timer
                        with timer('render time'):
                            builder.build({"libs": lib_info,
                                           "lib_paths": lib_paths})

                    # output_base_fs.makedir("libs", allow_recreate=True)
#.........这里部分代码省略.........
开发者ID:chrmorais,项目名称:moya,代码行数:103,代码来源:moyadoc.py

示例4: Filesystem

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
class Filesystem(drink.ListPage, PyFile):

    drink_name = "Server folder"

    local_path = ""

    mime = "folder"

    hidden_class = True

    default_action = "edit"

    path = ""

    editable_fields = drink.ListPage.editable_fields.copy()
    editable_fields.update({"local_path": drink.types.Text("Local folder path", group="a")})

    def serialize(self):
        drink.ListPage.serialize(recurse=False)
        return d

    def __init__(self, name, rootpath):
        self.fd = None
        drink.ListPage.__init__(self, name, rootpath)
        self._make_fd()
        PyFile.__init__(self, self, rootpath, self.id, self.id, None)

    def _edit(self):
        r = drink.ListPage._edit(self)
        self.fd = None
        self._make_fd()
        if self.default_action == "edit" and self.fd:
            self.default_action = "view"
        return r

    def _make_fd(self):
        if self.local_path and not self.fd:
            try:
                self.fd = OSFS(self.local_path, thread_synchronize=True)
            except fs.errors.ResourceNotFoundError:
                self.fd = None

    view = PyFile.view

    def keys(self):
        if self.fd:
            try:
                return self.fd.listdir()
            except (fs.errors.ResourceNotFoundError, fs.errors.PermissionDeniedError):
                return []
        else:
            return []

    iterkeys = keys

    def __getattr__(self, name):
        return drink.Model.__getattribute__(self, name)

    def __getitem__(self, name):
        if name in self._properties:
            raise KeyError()
        return PyFile(self, self.path, name, name, self.fd)
开发者ID:fdev31,项目名称:drink,代码行数:64,代码来源:filesystem.py

示例5: OSFS

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
    return url


try:
    src = sys.argv[1]
    dst = sys.argv[2]
except IndexError:
    src = '~/projects/linkstop/webapp/linkstop/media/faviconsx'
    dst = '~/projects/linkstop/webapp/linkstop/media/favicons'

src_fs = OSFS(src)
dst_fs = OSFS(dst)

count = 0
max_count = 2
for path in src_fs.listdir(dirs_only=True):
    icon_fs = src_fs.opendir(path)
    if icon_fs.isfile('scan.pik'):
        try:
            icon = pickle.load(icon_fs.open('scan.pik'))
        except Exception, e:
            print "%s (%s)" % (str(e), path)
            continue
        normalized_url = icon['normalized_url']
        out_dir = hash_path(normalized_url) + '/' + url_to_filename(normalized_url)
        print out_dir

        dest_dir_fs = dst_fs.makeopendir(out_dir, recursive=True)


        movedir(icon_fs, dest_dir_fs, overwrite=True, ignore_errors=True)
开发者ID:willmcgugan,项目名称:Locidesktop,代码行数:33,代码来源:shardfavicons.py

示例6: Timeline

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
class Timeline(object):
    """A timeline is a sequence of timestamped events."""

    def __init__(self, path, name, max_events=None):
        self.path = path
        self.name = name
        self.fs = OSFS(path, create=True)
        self.max_events = max_events

    def __repr__(self):
        return "Timeline({!r}, {!r}, max_events={!r})".format(self.path, self.name, self.max_events)

    def new_event(self, event_type, timestamp=None, *args, **kwargs):
        """Create and return an event, to be used as a context manager"""
        if self.max_events is not None:
            size = len(self.fs.listdir(wildcard="*.json"))
            if size >= self.max_events:
                raise TimelineFullError("The timeline has reached its maximum size")

        if timestamp is None:
            timestamp = int(time() * 1000.0)
        try:
            event_cls = _event_registry[event_type]
        except KeyError:
            raise UnknownEventError("No event type '{}'".format(event_type))

        # Make an event id that we can be confident it's unique
        token = str(randint(0, 2 ** 31))
        event_id = kwargs.pop('event_id', None) or "{}_{}_{}".format(event_type, timestamp, token)
        event = event_cls(self, event_id, timestamp, *args, **kwargs)
        log.debug('new event {!r}'.format(event))
        return event

    def new_photo(self, file, filename=None, ext=None, **kwargs):
        """Create a new photo object"""
        event = self.new_event('IMAGE', **kwargs)

        if hasattr(file, 'getvalue'):
            bytes = file.getvalue()
        elif file is not None:
            if isinstance(file, text_type):
                with open(file, 'rb') as f:
                    bytes = f.read()
            else:
                bytes = file.read()
        else:
            if bytes is None:
                raise ValueError("A value for 'file' or 'bytes' is required")
        event.attach_bytes(bytes, name='photo', filename=filename, ext=ext)
        return event

    def get_events(self, sort=True):
        """Get all accumulated events"""
        events = []
        for event_filename in self.fs.listdir(wildcard="*.json"):
            with self.fs.open(event_filename, 'rb') as f:
                event = loads(f.read().decode('utf-8'))
                events.append(event)
        if sort:
            # sort by timestamp
            events.sort(key=itemgetter('timestamp'))
        return events

    def clear_all(self):
        """Clear all stored events"""
        for filename in self.fs.listdir(wildcard="*.json"):
            try:
                self.fs.remove(filename)
            except FSError:
                pass

    def clear_events(self, event_ids):
        """Clear any events that have been processed"""
        for event_id in event_ids:
            filename = "{}.json".format(event_id)
            try:
                self.fs.remove(filename)
            except FSError:
                pass

    def _write_event(self, event_id, event):
        if hasattr(event, 'to_data'):
            event = event.to_data()
        event['event_id'] = event_id
        event_json = dumps(event, indent=4).encode('utf-8')
        filename = "{}.json".format(event_id)
        with self.fs.open(filename, 'wb') as f:
            f.write(event_json)
开发者ID:alextgn63,项目名称:dataplicity,代码行数:90,代码来源:timeline.py

示例7: log_folder

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
def log_folder():
    log_dir = log_folder_directories['0']
    folder = OSFS(log_dir)
    test_n = len(list(n for n in folder.listdir() if n.startswith('test')))
    return log_dir + "/test" + str(test_n + 1)
开发者ID:MehdiAB161,项目名称:Autoencoder-Stability,代码行数:7,代码来源:tools.py

示例8: summary_folder

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
def summary_folder(name):
    logdir = summary_folder_directories['0'] + name
    folder = OSFS(logdir)
    test_n = len(list(n for n in folder.listdir() if n.startswith('test')))
    return logdir + "/test" + str(test_n + 1)
开发者ID:MehdiAB161,项目名称:Autoencoder-Stability,代码行数:7,代码来源:tools.py

示例9: OSFS

# 需要导入模块: from fs.osfs import OSFS [as 别名]
# 或者: from fs.osfs.OSFS import listdir [as 别名]
#!/usr/bin/env python
import sys
from fs.osfs import OSFS
import Image

img_fs = OSFS(sys.argv[1])

imgs = []

for path in img_fs.listdir(wildcard='*.png'):
    img = Image.open(img_fs.getsyspath(path))
    size = img.size[0]

    if size != 16:
        continue

    imgs.append((path, img))

sprite = Image.new('RGBA', (16, len(imgs)*16))

imgs.sort(key=lambda i:i[0])

sprite_text_f = img_fs.open('sprites.txt', 'wt')

for i, (path, img) in enumerate(imgs):
    y = i*16
    sprite.paste(img, (0, y))
    sprite_text_f.write( "%i\t%s\n" % (y, path))

sprite.save(img_fs.getsyspath('sprites.png'))
开发者ID:willmcgugan,项目名称:Locidesktop,代码行数:32,代码来源:makesprites.py


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