本文整理汇总了Python中posixpath.relpath方法的典型用法代码示例。如果您正苦于以下问题:Python posixpath.relpath方法的具体用法?Python posixpath.relpath怎么用?Python posixpath.relpath使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类posixpath
的用法示例。
在下文中一共展示了posixpath.relpath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_webrelpath
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def make_webrelpath(path):
"""
Forcefully make *path* into a web-suitable relative path. This will strip
off leading and trailing directory separators.
.. versionadded:: 1.14.0
:param str path: The path to convert into a web-suitable relative path.
:return: The converted path.
:rtype: str
"""
if not path.startswith(webpath.sep):
path = webpath.sep + path
path = webpath.relpath(path, webpath.sep)
if path == webpath.curdir:
path = ''
return path
示例2: test_relpath
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def test_relpath(self):
(real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar")
try:
curdir = os.path.split(os.getcwd())[-1]
self.assertRaises(ValueError, posixpath.relpath, "")
self.assertEqual(posixpath.relpath("a"), "a")
self.assertEqual(posixpath.relpath(posixpath.abspath("a")), "a")
self.assertEqual(posixpath.relpath("a/b"), "a/b")
self.assertEqual(posixpath.relpath("../a/b"), "../a/b")
self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a")
self.assertEqual(posixpath.relpath("a/b", "../c"), "../"+curdir+"/a/b")
self.assertEqual(posixpath.relpath("a", "b/c"), "../../a")
self.assertEqual(posixpath.relpath("a", "a"), ".")
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x/y/z"), '../../../foo/bar/bat')
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/foo/bar"), 'bat')
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/"), 'foo/bar/bat')
self.assertEqual(posixpath.relpath("/", "/foo/bar/bat"), '../../..')
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x"), '../foo/bar/bat')
self.assertEqual(posixpath.relpath("/x", "/foo/bar/bat"), '../../../x')
self.assertEqual(posixpath.relpath("/", "/"), '.')
self.assertEqual(posixpath.relpath("/a", "/a"), '.')
self.assertEqual(posixpath.relpath("/a/b", "/a/b"), '.')
finally:
os.getcwd = real_getcwd
示例3: _get_project_from_path
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def _get_project_from_path(full_path):
"""
Split the absolute path in root_path and project_path using the top_path function in Settings()
Args:
full_path (str): absolute path
Returns:
str, str: root_path, project_path
"""
root = Settings().top_path(full_path)
if root is not None:
pr_path = posixpath.relpath(full_path, root)
return root, pr_path
else:
return None, full_path
示例4: _RelocateApp
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def _RelocateApp(device, package_name, relocate_to):
"""A context manager that relocates an app while in scope."""
relocation_map = {}
system_package_paths = _FindSystemPackagePaths(device, [package_name])
if system_package_paths:
relocation_map = {
p: posixpath.join(relocate_to, posixpath.relpath(p, '/'))
for p in system_package_paths
}
relocation_dirs = [
posixpath.dirname(d)
for _, d in relocation_map.iteritems()
]
device.RunShellCommand(['mkdir', '-p'] + relocation_dirs,
check_return=True)
_MoveApp(device, relocation_map)
else:
logger.info('No system package "%s"', package_name)
try:
yield
finally:
_MoveApp(device, {v: k for k, v in relocation_map.iteritems()})
示例5: test_relpath
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def test_relpath(self):
(real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar")
try:
curdir = os.path.split(os.getcwd())[-1]
self.assertRaises(ValueError, posixpath.relpath, "")
self.assertEqual(posixpath.relpath("a"), "a")
self.assertEqual(posixpath.relpath(posixpath.abspath("a")), "a")
self.assertEqual(posixpath.relpath("a/b"), "a/b")
self.assertEqual(posixpath.relpath("../a/b"), "../a/b")
self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a")
self.assertEqual(posixpath.relpath("a/b", "../c"),
"../"+curdir+"/a/b")
self.assertEqual(posixpath.relpath("a", "b/c"), "../../a")
self.assertEqual(posixpath.relpath("a", "a"), ".")
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x/y/z"), '../../../foo/bar/bat')
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/foo/bar"), 'bat')
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/"), 'foo/bar/bat')
self.assertEqual(posixpath.relpath("/", "/foo/bar/bat"), '../../..')
self.assertEqual(posixpath.relpath("/foo/bar/bat", "/x"), '../foo/bar/bat')
self.assertEqual(posixpath.relpath("/x", "/foo/bar/bat"), '../../../x')
self.assertEqual(posixpath.relpath("/", "/"), '.')
self.assertEqual(posixpath.relpath("/a", "/a"), '.')
self.assertEqual(posixpath.relpath("/a/b", "/a/b"), '.')
finally:
os.getcwd = real_getcwd
示例6: dir
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def dir(self, prefix=None, status=None):
if prefix is None or isinstance(prefix, str):
prefixes = [prefix]
else:
prefixes = prefix
assert all([prefix is None or isinstance(prefix, str) for prefix in prefixes]), "All path prefixes must be strings."
prefixes = [prefix if prefix is None else posixpath.relpath(prefix) for prefix in prefixes]
if isinstance(status, str):
if status == 'all':
status = [self.PostStatus.DRAFT, self.PostStatus.SUBMITTED, self.PostStatus.PUBLISHED, self.PostStatus.UNPUBLISHED]
else:
raise ValueError('Status alias `{}` not recognised.'.format(status))
if status is not None and not isinstance(status, list):
status = [status]
elif status is None:
status = [self.PostStatus.PUBLISHED]
# Use old syntax for "yielding from" to maintain support for python 2
for prefix in prefixes:
for path in self._dir(prefix=prefix, statuses=status):
yield path
示例7: listdir
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def listdir(self, name):
path = self._normalize_name(self._clean_name(name))
# The path needs to end with a slash, but if the root is empty, leave
# it.
if path and not path.endswith('/'):
path += '/'
directories = []
files = []
paginator = self.connection.meta.client.get_paginator('list_objects')
pages = paginator.paginate(Bucket=self.bucket_name, Delimiter='/', Prefix=path)
for page in pages:
for entry in page.get('CommonPrefixes', ()):
directories.append(posixpath.relpath(entry['Prefix'], path))
for entry in page.get('Contents', ()):
files.append(posixpath.relpath(entry['Key'], path))
return directories, files
示例8: log_artifacts
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def log_artifacts(self, local_dir, artifact_path=None):
(container, _, dest_path) = self.parse_wasbs_uri(self.artifact_uri)
container_client = self.client.get_container_client(container)
if artifact_path:
dest_path = posixpath.join(dest_path, artifact_path)
local_dir = os.path.abspath(local_dir)
for (root, _, filenames) in os.walk(local_dir):
upload_path = dest_path
if root != local_dir:
rel_path = os.path.relpath(root, local_dir)
upload_path = posixpath.join(dest_path, rel_path)
for f in filenames:
remote_file_path = posixpath.join(upload_path, f)
local_file_path = os.path.join(root, f)
with open(local_file_path, "rb") as file:
container_client.upload_blob(remote_file_path, file)
示例9: list_artifacts
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def list_artifacts(self, path=None):
from azure.storage.blob._models import BlobPrefix
(container, _, artifact_path) = self.parse_wasbs_uri(self.artifact_uri)
container_client = self.client.get_container_client(container)
dest_path = artifact_path
if path:
dest_path = posixpath.join(dest_path, path)
infos = []
prefix = dest_path + "/"
results = container_client.walk_blobs(name_starts_with=prefix)
for r in results:
if not r.name.startswith(artifact_path):
raise MlflowException(
"The name of the listed Azure blob does not begin with the specified"
" artifact path. Artifact path: {artifact_path}. Blob name:"
" {blob_name}".format(artifact_path=artifact_path, blob_name=r.name))
if isinstance(r, BlobPrefix): # This is a prefix for items in a subdirectory
subdir = posixpath.relpath(path=r.name, start=artifact_path)
if subdir.endswith("/"):
subdir = subdir[:-1]
infos.append(FileInfo(subdir, True, None))
else: # Just a plain old blob
file_name = posixpath.relpath(path=r.name, start=artifact_path)
infos.append(FileInfo(file_name, False, r.size))
return sorted(infos, key=lambda f: f.path)
示例10: __init__
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def __init__(self, artifact_uri):
super(DatabricksArtifactRepository, self).__init__(artifact_uri)
if not artifact_uri.startswith('dbfs:/'):
raise MlflowException(message='DatabricksArtifactRepository URI must start with dbfs:/',
error_code=INVALID_PARAMETER_VALUE)
if not is_databricks_acled_artifacts_uri(artifact_uri):
raise MlflowException(message=('Artifact URI incorrect. Expected path prefix to be'
' databricks/mlflow-tracking/path/to/artifact/..'),
error_code=INVALID_PARAMETER_VALUE)
self.run_id = self._extract_run_id(self.artifact_uri)
# Fetch the artifact root for the MLflow Run associated with `artifact_uri` and compute
# the path of `artifact_uri` relative to the MLflow Run's artifact root
# (the `run_relative_artifact_repo_root_path`). All operations performed on this artifact
# repository will be performed relative to this computed location
artifact_repo_root_path = extract_and_normalize_path(artifact_uri)
run_artifact_root_uri = self._get_run_artifact_root(self.run_id)
run_artifact_root_path = extract_and_normalize_path(run_artifact_root_uri)
run_relative_root_path = posixpath.relpath(
path=artifact_repo_root_path, start=run_artifact_root_path
)
# If the paths are equal, then use empty string over "./" for ListArtifact compatibility.
self.run_relative_artifact_repo_root_path = \
"" if run_artifact_root_path == artifact_repo_root_path else run_relative_root_path
示例11: _process
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def _process(self, input_pack: MultiPack):
multi_out_dir = os.path.join(self.configs.output_dir, self.multi_base)
pack_out_dir = os.path.join(self.configs.output_dir, self.pack_base_out)
for pack in input_pack.packs:
pack_out = write_pack(
pack, pack_out_dir, self.pack_name(pack), self.configs.indent,
self.configs.zip_pack, self.configs.overwrite,
self.configs.drop_record)
self.pack_idx_out.write(
f'{pack.meta.pack_id}\t'
f'{posixpath.relpath(pack_out, self.configs.output_dir)}\n')
multi_out = write_pack(
input_pack, multi_out_dir,
self.multipack_name(input_pack), self.configs.indent,
self.configs.zip_pack, self.configs.overwrite,
self.configs.drop_record
)
self.multi_idx_out.write(
f'{input_pack.meta.pack_id}\t'
f'{posixpath.relpath(multi_out, self.configs.output_dir)}\n')
示例12: import_from_path
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def import_from_path(self, path, recursive=True):
"""
Args:
path:
recursive:
Returns:
"""
if os.path.abspath(path):
search_path = posixpath.normpath(path.replace("//", "/"))
else:
search_path = posixpath.normpath(
posixpath.join(self.path, path.replace("//", "/"))
)
if recursive:
for x in os.walk(search_path):
self._calculation_validation(
x[0], x[2], rel_path=posixpath.relpath(x[0], search_path)
)
else:
abs_path = "/".join(search_path.replace("\\", "/").split("/")[:-1])
rel_path = posixpath.relpath(abs_path, self.path)
self._calculation_validation(
search_path, os.listdir(search_path), rel_path=rel_path
)
示例13: makeNodesRelative
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def makeNodesRelative(nodes, knobTypes):
result = { 'warnings': [], 'replacements': [], 'projectFolder': None}
projectfile = nuke.root()['name'].value()
if projectfile =="":
result['warnings'].append('Please save the nuke script before running this function such that it has a valid path.')
return result
projectFolderAbsolute = posixpath.dirname(projectfile)
result['projectFolder'] = projectFolderAbsolute
projectFolderRelative = "[file dirname [value root.name]]"
for n in nodes:
for k in knobTypes:
if n.knob(k):
originalFilePath = n[k].value()
if n[k].isAnimated():
result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since the knob is animated')
elif n[k].hasExpression():
result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since the knob has an expression')
elif originalFilePath.strip()=="":
#result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since it is empty')
pass
elif originalFilePath.startswith(projectFolderRelative):
result['warnings'].append("Didn't replace "+k+' of node '+n['name'].value()+' since it is already a relative path:\n'+ __removePrefix(originalFilePath,projectFolderRelative))
else:
relativeFilePath = posixpath.relpath(originalFilePath,projectFolderAbsolute)
n[k].setValue(projectFolderRelative + '/' +relativeFilePath)
result['replacements'].append(k+' of '+ n['name'].value()+':\n'+relativeFilePath)
return result
示例14: _GetStaleDirectories
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def _GetStaleDirectories(self, host_path, device_path):
"""Gets a list of stale directories on the device.
Args:
host_path: an absolute path of a directory on the host
device_path: an absolute path of a directory on the device
Returns:
A list containing absolute paths to directories on the device that are
considered stale.
"""
def get_device_dirs(path):
directories = set()
command = _RECURSIVE_DIRECTORY_LIST_SCRIPT % cmd_helper.SingleQuote(path)
# We use shell=True to evaluate the command as a script through the shell,
# otherwise RunShellCommand tries to interpret it as the name of a (non
# existent) command to run.
for line in self.RunShellCommand(
command, shell=True, check_return=True):
directories.add(posixpath.relpath(posixpath.normpath(line), path))
return directories
def get_host_dirs(path):
directories = set()
if not os.path.isdir(path):
return directories
for root, _, _ in os.walk(path):
if root != path:
# Strip off the top level directory so we can compare the device and
# host.
directories.add(
os.path.relpath(root, path).replace(os.sep, posixpath.sep))
return directories
host_dirs = get_host_dirs(host_path)
device_dirs = get_device_dirs(device_path)
stale_dirs = device_dirs - host_dirs
return [posixpath.join(device_path, d) for d in stale_dirs]
示例15: test_realpath_relative
# 需要导入模块: import posixpath [as 别名]
# 或者: from posixpath import relpath [as 别名]
def test_realpath_relative(self):
try:
os.symlink(posixpath.relpath(ABSTFN+"1"), ABSTFN)
self.assertEqual(realpath(ABSTFN), ABSTFN+"1")
finally:
support.unlink(ABSTFN)