Python源码示例:pathlib.WindowsPath()

示例1
def is_7zfile(file: Union[BinaryIO, str, pathlib.Path]) -> bool:
    """Quickly see if a file is a 7Z file by checking the magic number.
    The file argument may be a filename or file-like object too.
    """
    result = False
    try:
        if isinstance(file, io.IOBase) and hasattr(file, "read"):
            result = SevenZipFile._check_7zfile(file)  # type: ignore  # noqa
        elif isinstance(file, str):
            with open(file, 'rb') as fp:
                result = SevenZipFile._check_7zfile(fp)
        elif isinstance(file, pathlib.Path) or isinstance(file, pathlib.PosixPath) or \
                isinstance(file, pathlib.WindowsPath):
            with file.open(mode='rb') as fp:  # type: ignore  # noqa
                result = SevenZipFile._check_7zfile(fp)
        else:
            raise TypeError('invalid type: file should be str, pathlib.Path or BinaryIO, but {}'.format(type(file)))
    except OSError:
        pass
    return result 
示例2
def test_symlink_readlink_absolute(tmp_path):
    origin = tmp_path / 'parent' / 'original.txt'
    origin.parent.mkdir(parents=True, exist_ok=True)
    with origin.open('w') as f:
        f.write("Original")
    slink = tmp_path / "target" / "link"
    slink.parent.mkdir(parents=True, exist_ok=True)
    target = origin.resolve()
    slink.symlink_to(target, False)
    if sys.platform.startswith("win"):
        assert py7zr.win32compat.readlink(str(tmp_path / "target" / "link")) == PATH_PREFIX + str(target)
        assert py7zr.helpers.readlink(str(slink)) == PATH_PREFIX + str(target)
        assert py7zr.helpers.readlink(slink) == pathlib.WindowsPath(PATH_PREFIX + str(target))
    else:
        assert py7zr.helpers.readlink(str(slink)) == str(target)
        assert py7zr.helpers.readlink(slink) == target
    assert slink.open('r').read() == 'Original' 
示例3
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
示例4
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath) 
示例5
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
示例6
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath) 
示例7
def getStem(name):
    target_name = None

    if platform.system() == 'Windows':
        target_name = WindowsPath(name).stem
    elif platform.system() == 'Linux':
        target_name = PosixPath(name).stem
    else:
        print("Operation System: " + str(platform.system()) + ", unfortunately not supported here")
        raise Exception('Unknown OS: ' + platform.system())

    return target_name 
示例8
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
示例9
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath) 
示例10
def test_junction_readlink(tmp_path):
    target = tmp_path / 'parent'
    target.mkdir(parents=True, exist_ok=True)
    with target.joinpath("original.txt").open('w') as f:
        f.write("Original")
    junction = tmp_path / "target" / "link"
    junction.parent.mkdir(parents=True, exist_ok=True)
    os.system('mklink /J %s %s' % (str(junction), str(target.resolve())))
    assert not os.path.islink(str(junction))
    assert py7zr.win32compat.is_reparse_point(str(junction))
    assert py7zr.win32compat.readlink(str(junction)) == PATH_PREFIX + str(target.resolve())
    assert py7zr.helpers.readlink(str(junction)) == PATH_PREFIX + str(target.resolve())
    assert py7zr.win32compat.is_reparse_point(junction)
    assert py7zr.win32compat.readlink(junction) == pathlib.WindowsPath(PATH_PREFIX + str(target.resolve()))
    assert py7zr.helpers.readlink(junction) == pathlib.WindowsPath(PATH_PREFIX + str(target.resolve())) 
示例11
def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        return cls._from_parts(args).expanduser().expandnamed(
            host=kwargs.get('host', None)) 
示例12
def __new__(cls, path=None, name=None, suffix=None, prefix=None, dir=None):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        filename = request_answer_from_controller(
            ['sos_tempfile', path, name, suffix, prefix, dir])
        return cls._from_parts([filename]) 
示例13
def to_file(self, data: str,
                filename: Union[pathlib.Path, pathlib.WindowsPath],
                encryption="json", indent=4):
        if encryption == "json":
            encrypted_dict = self.to_dict(data)
            data_json = json.dumps(encrypted_dict, indent=indent)
            filename.write_text(data_json)

        elif encryption == "bytes":
            encrypted_data = self.to_bytes(data)
            filename.write_bytes(encrypted_data)

        else:
            raise ValueError("encryption must be \"json\" or \"bytes\"..") 
示例14
def from_file(self, filename: Union[pathlib.Path, pathlib.WindowsPath],
                  encryption="json"):
        if encryption == "json":
            encrypted_json = filename.read_text()
            encrypted_dict = json.loads(encrypted_json)

            return self.from_dict(encrypted_dict)

        elif encryption == "bytes":
            encrypted_data = filename.read_bytes()
    
            return self.from_bytes(encrypted_data)

        else:
            raise ValueError("encryption must be \"json\" or \"bytes\".") 
示例15
def detect_file_encryption(filename: Union[pathlib.Path, pathlib.WindowsPath]):
    file = filename.read_bytes()
    try:
        file = json.loads(file)
        if "adp_token" in file:
            return False
        elif "ciphertext" in file:
            return "json"
    except UnicodeDecodeError:
        return "bytes" 
示例16
def _check_filename(value) -> Union[pathlib.Path, pathlib.WindowsPath]:
    if not isinstance(value, (pathlib.Path, pathlib.WindowsPath)):
        try:
            return pathlib.Path(value)
        except NotImplementedError:
            return pathlib.WindowsPath(value)
        except:
            raise Exception("File error") 
示例17
def set_file_logger(filename: str, level: Union[str, int] = 0) -> None:
    """Set logging level and filename for the file handler."""
    try:
        filename = pathlib.Path(filename)
    except NotImplementedError:
        filename = pathlib.WindowsPath(filename)

    file_handler = logging.FileHandler(filename)
    file_handler.setFormatter(log_formatter)
    file_handler.set_name("FileLogger")
    logger.addHandler(file_handler)
    _setLevel(file_handler, level) 
示例18
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath) 
示例19
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath)