本文整理匯總了Python中pathlib.Path.resolve方法的典型用法代碼示例。如果您正苦於以下問題:Python Path.resolve方法的具體用法?Python Path.resolve怎麽用?Python Path.resolve使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pathlib.Path
的用法示例。
在下文中一共展示了Path.resolve方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: main
# 需要導入模塊: from pathlib import Path [as 別名]
# 或者: from pathlib.Path import resolve [as 別名]
def main():
args = get_args()
# create output dir if not exist
dir = Path.resolve(Path(args.out_dir))
dir.mkdir(parents=True, exist_ok=True)
# open bulkfile
bulkfile = h5py.File(args.bulk_file, "r")
# get run_id and sf
sf = int(bulkfile["UniqueGlobalKey"]["context_tags"].attrs["sample_frequency"].decode('utf8'))
run_id = bulkfile["UniqueGlobalKey"]["tracking_id"].attrs["run_id"].decode('utf8')
fields = ['coords', 'run_id']
fused_df = pd.read_csv(args.fused, sep='\t', usecols=fields)
# limit to matching run
fused_df = fused_df[fused_df['run_id'] == run_id]
for index, row in tqdm(fused_df.iterrows(), total=fused_df.shape[0]):
line = row['coords']
coords = line.split(":")
times = coords[1].split("-")
channel_num = coords[0]
start_time, end_time = int(times[0]), int(times[1])
plot = create_figure(channel_num, start_time, end_time, sf, bulkfile, args.bulk_file)
line = '{c}.png'.format(c=line.replace(':', '_'))
write_path = Path(dir / line)
export_png(plot, filename=write_path)
return
示例2: _sanitize_path
# 需要導入模塊: from pathlib import Path [as 別名]
# 或者: from pathlib.Path import resolve [as 別名]
def _sanitize_path(filepath):
try:
path_root = Path(getattr(settings, 'SENDFILE_ROOT', None))
except TypeError:
raise ImproperlyConfigured('You must specify a value for SENDFILE_ROOT')
filepath_obj = Path(filepath)
# get absolute path
# Python 3.5: Path.resolve() has no `strict` kwarg, so use pathmod from an
# already instantiated Path object
filepath_abs = Path(filepath_obj._flavour.pathmod.normpath(str(path_root / filepath_obj)))
# if filepath_abs is not relative to path_root, relative_to throws an error
try:
filepath_abs.relative_to(path_root)
except ValueError:
raise Http404('{} wrt {} is impossible'.format(filepath_abs, path_root))
return filepath_abs
示例3: resolve_path
# 需要導入模塊: from pathlib import Path [as 別名]
# 或者: from pathlib.Path import resolve [as 別名]
def resolve_path(path: Path) -> Path:
"""
Resolves the given *path* **strictly**, throwing a
:class:`FileNotFoundError` if it is not resolvable.
This function exists only because Path.resolve()'s default behaviour
changed from strict to not strict in 3.5 → 3.6. In most places we want the
strict behaviour, but the "strict" keyword argument didn't exist until 3.6
when the behaviour became optional (and not the default).
All this function does is call ``path.resolve()`` on 3.5 and
``path.resolve(strict = True)`` on 3.6.
"""
if python_version >= (3,6):
# mypy doesn't know we did a version check
return path.resolve(strict = True) # type: ignore
else:
return path.resolve()
示例4: _load_config
# 需要導入模塊: from pathlib import Path [as 別名]
# 或者: from pathlib.Path import resolve [as 別名]
def _load_config(self, configfile):
config = Config()
if not configfile:
return config
configpath = Path(configfile)
try:
if not configpath.expanduser().resolve().exists():
logger.debug('Ignoring non existing config file %s', configfile)
return config
except FileNotFoundError:
# we are on python 3.5 and Path.resolve raised a FileNotFoundError
logger.debug('Ignoring non existing config file %s', configfile)
return config
try:
config.load(configpath)
logger.debug('Loaded config %s', configfile)
except Exception as e: # pylint: disable=broad-except
raise RuntimeError(
'Error while parsing config file {config}. Error was '
'{message}'.format(config=configfile, message=e)
)
return config
示例5: _convert_file_to_url
# 需要導入模塊: from pathlib import Path [as 別名]
# 或者: from pathlib.Path import resolve [as 別名]
def _convert_file_to_url(path):
try:
url_root = PurePath(getattr(settings, "SENDFILE_URL", None))
except TypeError:
return path
path_root = PurePath(settings.SENDFILE_ROOT)
path_obj = PurePath(path)
relpath = path_obj.relative_to(path_root)
# Python 3.5: Path.resolve() has no `strict` kwarg, so use pathmod from an
# already instantiated Path object
url = relpath._flavour.pathmod.normpath(str(url_root / relpath))
return quote(str(url))
示例6: workspace_from_url
# 需要導入模塊: from pathlib import Path [as 別名]
# 或者: from pathlib.Path import resolve [as 別名]
def workspace_from_url(self, mets_url, dst_dir=None, clobber_mets=False, mets_basename=None, download=False, src_baseurl=None):
"""
Create a workspace from a METS by URL (i.e. clone it).
Sets the mets.xml file
Arguments:
mets_url (string): Source mets URL
dst_dir (string, None): Target directory for the workspace
clobber_mets (boolean, False): Whether to overwrite existing mets.xml. By default existing mets.xml will raise an exception.
download (boolean, False): Whether to download all the files
src_baseurl (string, None): Base URL for resolving relative file locations
Returns:
Workspace
"""
if mets_url is None:
raise ValueError("Must pass 'mets_url' workspace_from_url")
# if mets_url is a relative filename, make it absolute
if is_local_filename(mets_url) and not Path(mets_url).is_absolute():
mets_url = str(Path(Path.cwd() / mets_url))
# if mets_basename is not given, use the last URL segment of the mets_url
if mets_basename is None:
mets_basename = nth_url_segment(mets_url, -1)
# If src_baseurl wasn't given, determine from mets_url by removing last url segment
if not src_baseurl:
last_segment = nth_url_segment(mets_url)
src_baseurl = remove_non_path_from_url(remove_non_path_from_url(mets_url)[:-len(last_segment)])
# resolve dst_dir
if not dst_dir:
if is_local_filename(mets_url):
log.debug("Deriving dst_dir %s from %s", Path(mets_url).parent, mets_url)
dst_dir = Path(mets_url).parent
else:
log.debug("Creating ephemeral workspace '%s' for METS @ <%s>", dst_dir, mets_url)
dst_dir = tempfile.mkdtemp(prefix=TMP_PREFIX)
# XXX Path.resolve is always strict in Python <= 3.5, so create dst_dir unless it exists consistently
if not Path(dst_dir).exists():
Path(dst_dir).mkdir(parents=True, exist_ok=False)
dst_dir = str(Path(dst_dir).resolve())
log.debug("workspace_from_url\nmets_basename='%s'\nmets_url='%s'\nsrc_baseurl='%s'\ndst_dir='%s'",
mets_basename, mets_url, src_baseurl, dst_dir)
self.download_to_directory(dst_dir, mets_url, basename=mets_basename, if_exists='overwrite' if clobber_mets else 'skip')
workspace = Workspace(self, dst_dir, mets_basename=mets_basename, baseurl=src_baseurl)
if download:
for f in workspace.mets.find_files():
workspace.download_file(f)
return workspace