本文整理汇总了Python中pathlib2.Path方法的典型用法代码示例。如果您正苦于以下问题:Python pathlib2.Path方法的具体用法?Python pathlib2.Path怎么用?Python pathlib2.Path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pathlib2
的用法示例。
在下文中一共展示了pathlib2.Path方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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()
示例2: wait_for_env_startup
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例3: test_no_setup_py_exits_but_pyproject_toml_does
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例4: test_islink
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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)
示例5: assert_islink
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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)
示例6: get_oasislmf_config_path
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例7: compute_sha256_for_file
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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()
示例8: compute_md5_for_file
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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()
示例9: _form_conf_path
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例10: run
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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!')
示例11: get_custom_dict
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例12: dump_flight_to_csv
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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))
示例13: ensure_extended_length_path
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例14: _force_symlink
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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
示例15: make_numbered_dir
# 需要导入模块: import pathlib2 [as 别名]
# 或者: from pathlib2 import Path [as 别名]
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)
)