Python pathlib.Path.resolve() Examples
The following are 6
code examples of pathlib.Path.resolve().
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 also want to check out all available functions/classes of the module
pathlib.Path
, or try the search function
.
Example #1
Source File: pod_plot.py From bulkvis with MIT License | 6 votes |
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
Example #2
Source File: utils.py From django-sendfile2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #3
Source File: util.py From cli with MIT License | 6 votes |
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()
Example #4
Source File: parser.py From gvm-tools with GNU General Public License v3.0 | 5 votes |
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
Example #5
Source File: utils.py From django-sendfile2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
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))
Example #6
Source File: resolver.py From core with Apache License 2.0 | 4 votes |
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