How to use the pathlib.PurePath function in pathlib

To help you get started, we’ve selected a few pathlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jdidion / xphyle / xphyle / paths.py View on Github external
Args:
        path: String to convert. May be a string path, a stdin/stdout/stderr
            placeholder, or file:// URL. If it is already a PurePath, it is
            returned without modification.
        access: The file access mode, to disambiguate stdin/stdout when `path`
            is the placeholder ('-').

    Returns:
        A PurePath instance. Except with 'path' is a PurePath or
        stdin/stdout/stderr placeholder, the actual return type is a Path
        instance.
    """
    if isinstance(path, str):
        path = convert_std_placeholder(path, access)
    if isinstance(path, PurePath):
        return cast(PurePath, path)

    url = parse_url(path)
    if url:
        if url.scheme == "file":
            return Path(url.path)
        else:
            raise IOError(f"Cannot convert URL {path} to path", path)

    return Path(path)
github aioworkers / aioworkers / tests / test_storage_fs.py View on Github external
storage = context.storage

    assert str(storage.raw_key(('1', '3', ('4',)))).endswith('1/3/4')
    assert str(storage.raw_key((PurePath('1'), '3', ('4',)))).endswith('1/3/4')

    with pytest.raises(TypeError):
        storage.raw_key(1)

    with pytest.raises(ValueError):
        storage.raw_key('../..')

    with pytest.raises(ValueError):
        storage.raw_key('/abs/path')

    with pytest.raises(ValueError):
        storage.raw_key(PurePath('/abs/path'))
github armadillica / flamenco / tests / test_job_compiler_blender_render.py View on Github external
def test_intermediate_path(self):
        from flamenco.job_compilers import blender_render

        job_doc = JobDocForTesting({
            '_created': self.created,
        })

        render_path = pathlib.PurePosixPath('/path/to/output')
        path = blender_render.intermediate_path(job_doc, render_path)
        self.assertEqual(
            pathlib.PurePath('/path/to/output__intermediate-2018-07-06_115233'),
            path
        )
github jdidion / xphyle / xphyle / paths.py View on Github external
Args:
            paths: List of paths, or a string with directories separated by
                `os.pathsep`.
        """

        def _as_path(p):
            check_std(p, error=True)
            s = str(p)
            if '"' in s:
                p = s.strip('"')
            return as_path(p)

        if isinstance(paths, str):
            paths = tuple(_as_path(path) for path in paths.split(os.pathsep))
        elif isinstance(paths, PurePath):
            paths = (paths,)
        else:
            paths = tuple(paths)

        self.search_path = paths + self.search_path
github eliasdoehne / stellaris-dashboard / stellarisdashboard / parsing / save_parser.py View on Github external
def __init__(self, save_parent_dir, game_name_prefix: str = ""):
        super().__init__(save_parent_dir, game_name_prefix)
        self._num_threads = config.CONFIG.threads
        self._pool = mp.Pool(
            processes=config.CONFIG.threads, initializer=_pool_worker_init
        )
        self._pending_results: Deque[Tuple[pathlib.PurePath, Any]] = collections.deque()
github zevaverbach / tatt / tatt / vendors / vendor.py View on Github external
def __init__(self, filepath):
        self._setup()
        if " " in filepath:
            raise exceptions.FormatError("Please don't put any spaces in the filename.")
        self.filepath = PurePath(filepath)
        self.basename = str(os.path.basename(self.filepath))
github cool-RR / python_toolbox / python_toolbox / zip_tools.py View on Github external
`ignored_patterns` are fnmatch-style patterns specifiying file-paths to
    ignore.

    Any empty sub-folders will be ignored.
    '''
    zip_path = pathlib.Path(zip_path)
    source_folder = pathlib.Path(source_folder).absolute()
    assert source_folder.is_dir()

    ignored_re_patterns = [re.compile(fnmatch.translate(ignored_pattern)) for
                           ignored_pattern in ignored_patterns]

    zip_name = zip_path.stem

    internal_pure_path = pathlib.PurePath(source_folder.name)

    with zip_module.ZipFile(str(zip_path), 'w', zip_module.ZIP_DEFLATED) \
                                                                   as zip_file:

        for root, subfolders, files in os.walk(str(source_folder)):
            root = pathlib.Path(root)
            subfolders = map(pathlib.Path, subfolders)
            files = map(pathlib.Path, files)

            for file_path in files:

                if any(ignored_re_pattern.match(root / file_path)
                                for ignored_re_pattern in ignored_re_patterns):
                    continue

                absolute_file_path = root / file_path
github scylladb / seastar / scripts / perftune.py View on Github external
def __learn_irqs(self):
        disk2irqs = {}

        for devices in list(self.__dir2disks.values()) + [ self.args.devs ]:
            for device in devices:
                # There could be that some of the given directories are on the same disk.
                # There is no need to rediscover IRQs of the disk we've already handled.
                if device in disk2irqs.keys():
                    continue

                udev_obj = pyudev.Devices.from_device_file(self.__pyudev_ctx, "/dev/{}".format(device))
                dev_sys_path = udev_obj.sys_path
                split_sys_path = list(pathlib.PurePath(dev_sys_path).parts)

                # first part is always /sys/devices/pciXXX ...
                controller_path_parts = split_sys_path[0:4]

                # ...then there is a chain of one or more "domain:bus:device.function" followed by the storage device enumeration crap
                # e.g. /sys/devices/pci0000:00/0000:00:1f.2/ata2/host1/target1:0:0/1:0:0:0/block/sda/sda3 or
                #      /sys/devices/pci0000:00/0000:00:02.0/0000:02:00.0/host6/target6:2:0/6:2:0:0/block/sda/sda1
                # We want only the path till the last BDF including - it contains the IRQs information.

                patt = re.compile("^[0-9ABCDEFabcdef]{4}\:[0-9ABCDEFabcdef]{2}\:[0-9ABCDEFabcdef]{2}\.[0-9ABCDEFabcdef]$")
                for split_sys_path_branch in split_sys_path[4:]:
                    if patt.search(split_sys_path_branch):
                        controller_path_parts.append(split_sys_path_branch)
                    else:
                        break
github mherrmann / fbs / fbs / freeze / __init__.py View on Github external
args.extend(['--additional-hooks-dir', join(dirname(__file__), 'hooks')])
    if debug:
        args.extend(['--debug', 'all'])
        if is_mac():
            # Force generation of an .app bundle. Otherwise, PyInstaller skips
            # it when --debug is given.
            args.append('-w')
    hook_path = _generate_runtime_hook()
    args.extend(['--runtime-hook', hook_path])
    args.append(path(SETTINGS['main_module']))
    run(args, check=True)
    output_dir = path('target/' + app_name + ('.app' if is_mac() else ''))
    freeze_dir = path('${freeze_dir}')
    # In most cases, rename(src, dst) silently "works" when src == dst. But on
    # some Windows drives, it raises a FileExistsError. So check src != dst:
    if PurePath(output_dir) != PurePath(freeze_dir):
        rename(output_dir, freeze_dir)
github mangadventure / MangAdventure / groups / models.py View on Github external
def get_directory(self) -> PurePath:
        """
        Get the storage directory of the object.

        :return: A path relative to
                 :const:`~MangAdventure.settings.MEDIA_ROOT`.
        """
        return PurePath('groups', str(self.id))