Python pathlib2.Path() Examples

The following are 30 code examples for showing how to use pathlib2.Path(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module pathlib2 , or try the search function .

Example 1
Project: tox   Author: tox-dev   File: test_package_int.py    License: MIT License 6 votes vote down vote up
def run(cmd, package):
    result = cmd("--sdistonly", "-e", "py", "-v", "-v")
    result.assert_success(is_run_test_env=False)
    package_venv = (Path() / ".tox" / ".package").resolve()
    assert ".package create: {}".format(package_venv) in result.outlines, result.out
    assert "write config to {}".format(package_venv / ".tox-config1") in result.out, result.out
    package_path = (Path() / ".tox" / "dist" / package).resolve()
    assert package_path.exists()

    package_path.unlink()

    # second call re-uses
    result2 = cmd("--sdistonly", "-e", "py", "-v", "-v")

    result2.assert_success(is_run_test_env=False)
    assert (
        ".package reusing: {}".format(package_venv) in result2.outlines
    ), "Second call output:\n{}First call output:\n{}".format(result2.out, result.out)
    assert package_path.exists() 
Example 2
Project: tox   Author: tox-dev   File: test_parallel_interrupt.py    License: MIT License 6 votes vote down vote up
def wait_for_env_startup(process):
    """the environments will write files once they are up"""
    signal_files = [Path() / "a", Path() / "b"]
    found = False
    while True:
        if process.poll() is not None:
            break
        for signal_file in signal_files:
            if not signal_file.exists():
                break
        else:
            found = True
            break
    if not found or process.poll() is not None:
        missing = [f for f in signal_files if not f.exists()]
        out, _ = process.communicate()
        assert len(missing), out
        assert False, out 
Example 3
Project: tox   Author: tox-dev   File: test_z_cmdline.py    License: MIT License 6 votes vote down vote up
def test_no_setup_py_exits_but_pyproject_toml_does(cmd, initproj):
    initproj(
        "pkg123-0.7",
        filedefs={
            "tox.ini": """
            [testenv]
            commands=python -c "2 + 2"
        """,
        },
    )
    os.remove("setup.py")
    pathlib2.Path("pyproject.toml").touch()
    result = cmd()
    result.assert_fail()
    assert any(
        re.match(r".*ERROR.*pyproject.toml file found.*", line) for line in result.outlines
    ), result.outlines
    assert any(
        re.match(r".*To use a PEP 517 build-backend you are required to*", line)
        for line in result.outlines
    ), result.outlines 
Example 4
Project: testpath   Author: jupyter   File: test_asserts.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_islink(self):
        if os.name == 'nt':
            raise unittest.SkipTest('symlink')
        assert_islink(self.link_path, to=self.file_path)
        assert_islink(pathlib.Path(self.link_path),
                      to=pathlib.Path(self.file_path))
        assert_not_islink(self.file_path)
        
        with self.assertRaises(AssertionError) as c:
            assert_islink(self.file_path)
        self.assertIn('not a symlink', str(c.exception))
        
        with self.assertRaises(AssertionError) as c:
            assert_islink(self.link_path, to=self.dir_path)
        self.assertIn('target of', str(c.exception))
        
        with self.assertRaises(AssertionError):
            assert_not_islink(self.link_path) 
Example 5
Project: testpath   Author: jupyter   File: asserts.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def assert_islink(path, to=None, msg=None):
    """Assert that path exists and is a symlink.
    
    If to is specified, also check that it is the target of the symlink.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, False, msg)
    if not stat.S_ISLNK(st.st_mode):
        if msg is None:
            msg = "Path exists, but is not a symlink: %r" % path
        raise AssertionError(msg)
    
    if to is not None:
        to = _strpath(to)
        target = os.readlink(path)
        # TODO: Normalise the target to an absolute path?
        if target != to:
            if msg is None:
                msg = _link_target_msg.format(path=path, expected=to, actual=target)
            raise AssertionError(msg) 
Example 6
Project: OasisPlatform   Author: OasisLMF   File: tasks.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_oasislmf_config_path(model_id=None):
    conf_var = settings.get('worker', 'oasislmf_config', fallback=None)
    if not model_id:
        model_id = settings.get('worker', 'model_id', fallback=None)

    if conf_var:
        return conf_var

    if model_id:
        model_root = settings.get('worker', 'model_data_directory', fallback='/var/oasis/')
        model_specific_conf = Path(model_root, '{}-oasislmf.json'.format(model_id))
        if model_specific_conf.exists():
            return str(model_specific_conf)

    return str(Path(model_root, 'oasislmf.json'))


# Send notification back to the API Once task is read from Queue 
Example 7
Project: batch-shipyard   Author: Azure   File: util.py    License: MIT License 6 votes vote down vote up
def compute_sha256_for_file(file, as_base64, blocksize=65536):
    # type: (pathlib.Path, bool, int) -> str
    """Compute SHA256 hash for file
    :param pathlib.Path file: file to compute md5 for
    :param bool as_base64: return as base64 encoded string
    :param int blocksize: block size in bytes
    :rtype: str
    :return: SHA256 for file
    """
    hasher = hashlib.sha256()
    if isinstance(file, pathlib.Path):
        file = str(file)
    with open(file, 'rb') as filedesc:
        while True:
            buf = filedesc.read(blocksize)
            if not buf:
                break
            hasher.update(buf)
        if as_base64:
            return base64_encode_string(hasher.digest())
        else:
            return hasher.hexdigest() 
Example 8
Project: batch-shipyard   Author: Azure   File: util.py    License: MIT License 6 votes vote down vote up
def compute_md5_for_file(file, as_base64, blocksize=65536):
    # type: (pathlib.Path, bool, int) -> str
    """Compute MD5 hash for file
    :param pathlib.Path file: file to compute md5 for
    :param bool as_base64: return as base64 encoded string
    :param int blocksize: block size in bytes
    :rtype: str
    :return: md5 for file
    """
    hasher = hashlib.md5()
    if isinstance(file, pathlib.Path):
        file = str(file)
    with open(file, 'rb') as filedesc:
        while True:
            buf = filedesc.read(blocksize)
            if not buf:
                break
            hasher.update(buf)
        if as_base64:
            return base64_encode_string(hasher.digest())
        else:
            return hasher.hexdigest() 
Example 9
Project: batch-shipyard   Author: Azure   File: shipyard.py    License: MIT License 6 votes vote down vote up
def _form_conf_path(self, conf_var, prefix):
        """Form configuration file path with configdir if applicable
        :param CliContext self: this
        :param any conf_var: conf var
        :param str prefix: configuration file prefix
        :rtype: pathlib.Path
        :return: new configuration file path
        """
        # use configdir if available
        if conf_var is None:
            cd = self.configdir or '.'
            pathyaml = pathlib.Path(cd, '{}.yaml'.format(prefix))
            if pathyaml.exists():
                return pathyaml
            path = pathlib.Path(cd, '{}.yml'.format(prefix))
            if path.exists():
                return path
            path = pathlib.Path(cd, '{}.json'.format(prefix))
            if path.exists():
                return path
            return pathyaml
        else:
            return conf_var 
Example 10
Project: kubeflow-and-mlops   Author: aronchick   File: register.py    License: Apache License 2.0 6 votes vote down vote up
def run(model_path, model_name, tenant_id, service_principal_id,
        service_principal_password, subscription_id, resource_group, workspace, tags):
    auth_args = {
        'tenant_id': tenant_id,
        'service_principal_id': service_principal_id,
        'service_principal_password': service_principal_password
    }

    ws_args = {
        'auth': ServicePrincipalAuthentication(**auth_args),
        'subscription_id': subscription_id,
        'resource_group': resource_group
    }

    ws = Workspace.get(workspace, **ws_args)

    print(ws.get_details())

    print('\nSaving model {} to {}'.format(model_path, model_name))

    # Model Path needs to be relative
    model_path = relpath(model_path, '.')

    model = Model.register(ws, model_name=model_name, model_path=model_path, tags=tags)
    print('Done!') 
Example 11
Project: pyiron   Author: pyiron   File: external.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_custom_dict():
        folder = Path(".").cwd().parts[-1]
        hdf_file = Path(".").cwd().parents[1] / folder
        hdf_file = str(hdf_file) + ".h5"
        if Path(hdf_file).exists():
            hdf = FileHDFio(hdf_file)
            custom_dict = GenericParameters()
            for k, v in zip(
                hdf[folder + "/input/custom_dict/data_dict"]["Parameter"],
                hdf[folder + "/input/custom_dict/data_dict"]["Value"],
            ):
                custom_dict[k] = v
            return custom_dict
        elif Path("input.json").exists():
            with open("input.json") as f:
                return json.load(f)
        else:
            print(hdf_file, "not found")
            return None 
Example 12
Project: igc_lib   Author: xiadz   File: dumpers.py    License: MIT License 6 votes vote down vote up
def dump_flight_to_csv(flight, track_filename_local, thermals_filename_local):
    """Dumps flight data to CSV files.

    Args:
        flight: an igc_lib.Flight, the flight to be written
        track_filename_local: a string, the name of the output CSV with track data
        thermals_filename_local: a string, the name of the output CSV with thermal data
    """
    track_filename = Path(track_filename_local).expanduser().absolute()
    with track_filename.open('wt') as csv:
        csv.write(u"timestamp,lat,lon,bearing,bearing_change_rate,"
                  u"gsp,flying,circling\n")
        for fix in flight.fixes:
            csv.write(u"%f,%f,%f,%f,%f,%f,%s,%s\n" % (
                fix.timestamp, fix.lat, fix.lon,
                fix.bearing, fix.bearing_change_rate,
                fix.gsp, str(fix.flying), str(fix.circling)))

    thermals_filename = Path(thermals_filename_local).expanduser().absolute()
    with thermals_filename.open('wt') as csv:
        csv.write(u"timestamp_enter,timestamp_exit\n")
        for thermal in flight.thermals:
            csv.write(u"%f,%f\n" % (
                thermal.enter_fix.timestamp, thermal.exit_fix.timestamp)) 
Example 13
Project: pytest   Author: pytest-dev   File: pathlib.py    License: MIT License 6 votes vote down vote up
def ensure_extended_length_path(path: Path) -> Path:
    """Get the extended-length version of a path (Windows).

    On Windows, by default, the maximum length of a path (MAX_PATH) is 260
    characters, and operations on paths longer than that fail. But it is possible
    to overcome this by converting the path to "extended-length" form before
    performing the operation:
    https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation

    On Windows, this function returns the extended-length absolute version of path.
    On other platforms it returns path unchanged.
    """
    if sys.platform.startswith("win32"):
        path = path.resolve()
        path = Path(get_extended_length_path_str(str(path)))
    return path 
Example 14
Project: pytest   Author: pytest-dev   File: pathlib.py    License: MIT License 6 votes vote down vote up
def _force_symlink(
    root: Path, target: Union[str, PurePath], link_to: Union[str, Path]
) -> None:
    """helper to create the current symlink

    it's full of race conditions that are reasonably ok to ignore
    for the context of best effort linking to the latest test run

    the presumption being that in case of much parallelism
    the inaccuracy is going to be acceptable
    """
    current_symlink = root.joinpath(target)
    try:
        current_symlink.unlink()
    except OSError:
        pass
    try:
        current_symlink.symlink_to(link_to)
    except Exception:
        pass 
Example 15
Project: pytest   Author: pytest-dev   File: pathlib.py    License: MIT License 6 votes vote down vote up
def make_numbered_dir(root: Path, prefix: str) -> Path:
    """create a directory with an increased number as suffix for the given prefix"""
    for i in range(10):
        # try up to 10 times to create the folder
        max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)
        new_number = max_existing + 1
        new_path = root.joinpath("{}{}".format(prefix, new_number))
        try:
            new_path.mkdir()
        except Exception:
            pass
        else:
            _force_symlink(root, prefix + "current", new_path)
            return new_path
    else:
        raise OSError(
            "could not create numbered dir with prefix "
            "{prefix} in {root} after 10 tries".format(prefix=prefix, root=root)
        ) 
Example 16
Project: pytest   Author: pytest-dev   File: pathlib.py    License: MIT License 6 votes vote down vote up
def maybe_delete_a_numbered_dir(path: Path) -> None:
    """removes a numbered directory if its lock can be obtained and it does not seem to be in use"""
    path = ensure_extended_length_path(path)
    lock_path = None
    try:
        lock_path = create_cleanup_lock(path)
        parent = path.parent

        garbage = parent.joinpath("garbage-{}".format(uuid.uuid4()))
        path.rename(garbage)
        rm_rf(garbage)
    except OSError:
        #  known races:
        #  * other process did a cleanup at the same time
        #  * deletable folder was found
        #  * process cwd (Windows)
        return
    finally:
        # if we created the lock, ensure we remove it even if we failed
        # to properly remove the numbered dir
        if lock_path is not None:
            try:
                lock_path.unlink()
            except OSError:
                pass 
Example 17
Project: tox   Author: tox-dev   File: test_provision_int.py    License: MIT License 5 votes vote down vote up
def test_provision_missing(initproj, cmd):
    initproj(
        "pkg123-0.7",
        filedefs={
            "tox.ini": """\
                [tox]
                skipsdist=True
                minversion = 3.7.0
                requires =
                    setuptools == 40.6.3
                [testenv]
                commands=python -c "import sys; print(sys.executable); raise SystemExit(1)"
            """,
        },
    )
    result = cmd("-e", "py")
    result.assert_fail()
    assert "tox.exception.InvocationError" not in result.output()
    assert not result.err
    assert ".tox create: " in result.out
    assert ".tox installdeps: " in result.out
    assert "py create: " in result.out

    at = next(at for at, l in enumerate(result.outlines) if l.startswith("py run-test: ")) + 1
    meta_python = Path(result.outlines[at])
    assert meta_python.exists() 
Example 18
Project: configparser   Author: jaraco   File: test_configparser.py    License: MIT License 5 votes vote down vote up
def test_read_returns_file_list(self):
        if self.delimiters[0] != '=':
            self.skipTest('incompatible format')
        file1 = support.findfile("cfgparser.1")
        # check when we pass a mix of readable and non-readable files:
        cf = self.newconfig()
        parsed_files = cf.read([file1, "nonexistent-file"])
        self.assertEqual(parsed_files, [file1])
        self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
        # check when we pass only a filename:
        cf = self.newconfig()
        parsed_files = cf.read(file1)
        self.assertEqual(parsed_files, [file1])
        self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
        # check when we pass only a Path object:
        cf = self.newconfig()
        parsed_files = cf.read(pathlib.Path(file1))
        self.assertEqual(parsed_files, [file1])
        self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
        # check when we passed both a filename and a Path object:
        cf = self.newconfig()
        parsed_files = cf.read([pathlib.Path(file1), file1])
        self.assertEqual(parsed_files, [file1, file1])
        self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
        # check when we pass only missing files:
        cf = self.newconfig()
        parsed_files = cf.read(["nonexistent-file"])
        self.assertEqual(parsed_files, [])
        # check when we pass no files:
        cf = self.newconfig()
        parsed_files = cf.read([])
        self.assertEqual(parsed_files, []) 
Example 19
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    License: MIT License 5 votes vote down vote up
def resolve_from_str(input, root):
    assert not isinstance(input, Path), "would break on py2"
    root = Path(root)
    input = expanduser(input)
    input = expandvars(input)
    if isabs(input):
        return Path(input)
    else:
        return root.joinpath(input) 
Example 20
Project: python-netsurv   Author: sofia-netsurv   File: fixtures.py    License: MIT License 5 votes vote down vote up
def tempdir():
    tmpdir = tempfile.mkdtemp()
    try:
        yield pathlib.Path(tmpdir)
    finally:
        shutil.rmtree(tmpdir) 
Example 21
Project: python-netsurv   Author: sofia-netsurv   File: fixtures.py    License: MIT License 5 votes vote down vote up
def build_files(file_defs, prefix=pathlib.Path()):
    """Build a set of files/directories, as described by the

    file_defs dictionary.  Each key/value pair in the dictionary is
    interpreted as a filename/contents pair.  If the contents value is a
    dictionary, a directory is created, and the dictionary interpreted
    as the files within it, recursively.

    For example:

    {"README.txt": "A README file",
     "foo": {
        "__init__.py": "",
        "bar": {
            "__init__.py": "",
        },
        "baz.py": "# Some code",
     }
    }
    """
    for name, contents in file_defs.items():
        full_name = prefix / name
        if isinstance(contents, dict):
            full_name.mkdir()
            build_files(contents, prefix=full_name)
        else:
            if isinstance(contents, bytes):
                with full_name.open('wb') as f:
                    f.write(contents)
            else:
                with full_name.open('w') as f:
                    f.write(DALS(contents)) 
Example 22
Project: python-netsurv   Author: sofia-netsurv   File: pathlib.py    License: MIT License 5 votes vote down vote up
def resolve_from_str(input, root):
    assert not isinstance(input, Path), "would break on py2"
    root = Path(root)
    input = expanduser(input)
    input = expandvars(input)
    if isabs(input):
        return Path(input)
    else:
        return root.joinpath(input) 
Example 23
Project: python-netsurv   Author: sofia-netsurv   File: fixtures.py    License: MIT License 5 votes vote down vote up
def tempdir():
    tmpdir = tempfile.mkdtemp()
    try:
        yield pathlib.Path(tmpdir)
    finally:
        shutil.rmtree(tmpdir) 
Example 24
Project: testpath   Author: jupyter   File: test_asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_exists(self):
        assert_path_exists(self.file_path)
        assert_path_exists(pathlib.Path(self.file_path))
        assert_not_path_exists(self.nonexistant_path)
        
        with self.assertRaises(AssertionError):
            assert_path_exists(self.nonexistant_path)
        
        with self.assertRaises(AssertionError):
            assert_not_path_exists(self.file_path) 
Example 25
Project: testpath   Author: jupyter   File: test_asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_isdir(self):
        assert_isdir(self.dir_path)
        assert_isdir(pathlib.Path(self.dir_path))
        assert_not_isdir(self.file_path)
        
        with self.assertRaises(AssertionError):
            assert_isdir(self.file_path)
        
        with self.assertRaises(AssertionError):
            assert_not_isdir(self.dir_path) 
Example 26
Project: testpath   Author: jupyter   File: asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _strpath(p):
        if hasattr(p, '__fspath__'):
            return p.__fspath__()
        elif isinstance(p, Path):
            return str(p)
        return p 
Example 27
Project: testpath   Author: jupyter   File: asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _stat_for_assert(path, follow_symlinks=True, msg=None):
    stat = os.stat if follow_symlinks else os.lstat
    try:
        return stat(path)
    except OSError:
        if msg is None:
            msg = "Path does not exist, or can't be stat-ed: %r" % path
        raise AssertionError(msg) 
Example 28
Project: testpath   Author: jupyter   File: asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_isfile(path, follow_symlinks=True, msg=None):
    """Assert that path exists and is a regular file.
    
    With follow_symlinks=True, the default, this will pass if path is a symlink
    to a regular file. With follow_symlinks=False, it will fail in that case.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, follow_symlinks, msg)
    if not stat.S_ISREG(st.st_mode):
        if msg is None:
            msg = "Path exists, but is not a regular file: %r" % path
        raise AssertionError(msg) 
Example 29
Project: testpath   Author: jupyter   File: asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_not_isfile(path, follow_symlinks=True, msg=None):
    """Assert that path exists but is not a regular file.
    
    With follow_symlinks=True, the default, this will fail if path is a symlink
    to a regular file. With follow_symlinks=False, it will pass in that case.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, follow_symlinks, msg)
    if stat.S_ISREG(st.st_mode):
        if msg is None:
            msg = "Path is a regular file: %r" % path
        raise AssertionError(msg) 
Example 30
Project: testpath   Author: jupyter   File: asserts.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_isdir(path, follow_symlinks=True, msg=None):
    """Assert that path exists and is a directory.
    
    With follow_symlinks=True, the default, this will pass if path is a symlink
    to a directory. With follow_symlinks=False, it will fail in that case.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, follow_symlinks, msg)
    if not stat.S_ISDIR(st.st_mode):
        if msg is None:
            msg = "Path exists, but is not a directory: %r" % path
        raise AssertionError(msg)