Могу ли я создать объект файловой системы из указанного каталога c? - PullRequest
0 голосов
/ 13 апреля 2020

Нужно создать этот тип объекта (из kivy.properties & Kivy filechooser)

ObjectProperty(FileSystemLocal(), baseclass=FileSystemAbstract)

1 Ответ

0 голосов
/ 13 апреля 2020

Класс FileSystemLocal представляет собой простой интерфейс для некоторых методов os и os.path. Например, метод listdir() для FileSystemLocal - это просто вызов os.listdir(). Таким образом, он не указывает c для какого-либо каталога, он просто указывает c для локальных os и os.path. Итак, технически, ответ - нет.

Возможно, вы могли бы определить свой собственный подкласс FileSystemLocal, который соответствует вашим требованиям.

Вот пример расширения FileSystemLocal, в котором используется Speci c каталог:

from os import listdir
from os.path import (basename, join, getsize, isdir)

from sys import platform as core_platform

from kivy import Logger
from kivy.uix.filechooser import FileSystemAbstract, _have_win32file

platform = core_platform

_have_win32file = False
if platform == 'win':
    # Import that module here as it's not available on non-windows machines.
    try:
        from win32file import FILE_ATTRIBUTE_HIDDEN, GetFileAttributesExW, \
                              error
        _have_win32file = True
    except ImportError:
        Logger.error('filechooser: win32file module is missing')
        Logger.error('filechooser: we cant check if a file is hidden or not')


class FileSystemLocalDir(FileSystemAbstract):
    def __init__(self, **kwargs):
        self.dir = kwargs.pop('dir', None)
        super(FileSystemLocalDir, self).__init__()

    def listdir(self, fn):
        if self.dir is not None:
            fn = join(self.dir, fn)
        print('listdir for', fn)
        return listdir(fn)

    def getsize(self, fn):
        if self.dir is not None:
            fn = join(self.dir, fn)
        return getsize(fn)

    def is_hidden(self, fn):
        if self.dir is not None:
            fn = join(self.dir, fn)
        if platform == 'win':
            if not _have_win32file:
                return False
            try:
                return GetFileAttributesExW(fn)[0] & FILE_ATTRIBUTE_HIDDEN
            except error:
                # This error can occurred when a file is already accessed by
                # someone else. So don't return to True, because we have lot
                # of chances to not being able to do anything with it.
                Logger.exception('unable to access to <%s>' % fn)
                return True

        return basename(fn).startswith('.')

    def is_dir(self, fn):
        if self.dir is not None:
            fn = join(self.dir, fn)
        return isdir(fn)

Это может использоваться как:

fsld = FileSystemLocalDir(dir='/home')
print('dir:', fsld.dir)
print('listdir .:', fsld.listdir('.'))
print('listdir freddy:', fsld.listdir('freddy'))  # lists home directory of user `freddy`
print('listdir /usr:', fsld.listdir('/usr')) # this will list /usr regardless of the setting for self.dir

Примечание:

  • FileSystemLocalDir в значительной степени основан на FileSystemLocal.
  • dir= в конструкторе устанавливает каталог по умолчанию, к которому обращаются для всех методов FileSystemLocalDir.
  • Если аргумент dir= не предоставлен, FileSystemLocalDir эквивалентно FileSystemLocal.
  • Если аргумент любого метода FileSystemLocalDir начинается с /, он обрабатывается как абсолютный путь и предоставленный каталог по умолчанию игнорируется (это Эффект от использования os.join).
...