How to use pathlib - 10 common examples

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 packit-service / packit / tests / functional / test_srpm.py View on Github external
def test_srpm_command_for_path(upstream_or_distgit_path, tmp_path):
    with cwd(tmp_path):
        call_real_packit(parameters=["--debug", "srpm", str(upstream_or_distgit_path)])
        srpm_path = list(Path.cwd().glob("*.src.rpm"))[0]
        assert srpm_path.exists()
        build_srpm(srpm_path)
github vecto-ai / vecto / tests / test_setup.py View on Github external
def run_program(*args, glob: bool = False):
    """Run subprocess with given args. Use path globbing for each arg that contains an asterisk."""
    if glob:
        cwd = pathlib.Path.cwd()
        args = tuple(itertools.chain.from_iterable(
            list(str(_.relative_to(cwd)) for _ in cwd.glob(arg)) if '*' in arg else [arg]
            for arg in args))
    process = subprocess.Popen(args)
    process.wait()
    if process.returncode != 0:
        raise AssertionError('execution of {} returned {}'.format(args, process.returncode))
    return process
github emilkarlen / exactly / test / shellcheck_lib_test / test_case / phases / common.py View on Github external
def _check_line_number(self,
                           line_number: int,
                           tail: str,
                           expected_line_part: str,
                           num_line_number_previously_requested: int = 0
                           ):
        root_dir = pathlib.Path('root')
        logger = sut.PhaseLoggingPaths(root_dir, 'phase-identifier')
        for i in range(num_line_number_previously_requested):
            logger.for_line(line_number)
        actual = logger.for_line(line_number, tail=tail)
        self.assertEqual(logger.dir_path / expected_line_part,
                         actual)
github pyrates / usine / tests / integration / test_sftp.py View on Github external
def test_get_path(remotefile):
    get(remotefile, 'testget')
    with Path('testget').open() as f:
        assert f.read() == 'foobarééœ'
    Path('testget').unlink()
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 lxdock / lxdock / tests / unit / provisioners / test_puppet.py View on Github external
'module_path': 'test-puppet-modules'})
        provisioner.provision()

        assert mock_copy_dir.call_count == 2
        assert (Path('test-puppet-modules'),
                PurePosixPath(provisioner._guest_module_path)) in {
                    mock_copy_dir.call_args_list[0][0],
                    mock_copy_dir.call_args_list[1][0]}

        assert mock_run.call_count == 2
        assert mock_run.call_args_list[1][0][0] == [
            'sh', '-c',
            "puppet apply --modulepath {}:{} --detailed-exitcodes --manifestdir {} {}".format(
                PurePosixPath(provisioner._guest_module_path),
                PurePosixPath(provisioner._guest_default_module_path),
                PurePosixPath(provisioner._guest_manifests_path),
                PurePosixPath(provisioner._guest_manifests_path) / 'mani.pp')]
github AllenCellModeling / pytorch_fnet / tests / test_cli.py View on Github external
def project_dir():
    """Creates a mock user directory in which fnet commands would be used.

    Copies over example tifs to be used as test data and a dummy module
    containing dataset definitions.

    """
    path_pre = Path.cwd()
    path_tmp = Path(tempfile.mkdtemp())
    path_test_dir = Path(__file__).parent
    path_data_dir = path_test_dir.parent / 'data'
    Path.mkdir(path_tmp / 'data')
    for tif in ['EM_low.tif', 'MBP_low.tif']:
        shutil.copy(path_data_dir / tif, path_tmp / 'data')
    shutil.copy(path_test_dir / 'data' / 'dummymodule.py', path_tmp)
    os.chdir(path_tmp)
    yield path_tmp
    os.chdir(path_pre)
github facebook / buck / third-party / py / pathlib / test_pathlib.py View on Github external
def test_unsupported_flavour(self):
        if os.name == 'nt':
            self.assertRaises(NotImplementedError, pathlib.PosixPath)
        else:
            self.assertRaises(NotImplementedError, pathlib.WindowsPath)