Python os.fspath() Examples
The following are 30
code examples of os.fspath().
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
os
, or try the search function
.
Example #1
Source File: config.py From hypercorn with MIT License | 6 votes |
def from_toml(cls: Type["Config"], filename: FilePath) -> "Config": """Load the configuration values from a TOML formatted file. This allows configuration to be loaded as so .. code-block:: python Config.from_toml('config.toml') Arguments: filename: The filename which gives the path to the file. """ file_path = os.fspath(filename) with open(file_path) as file_: data = toml.load(file_) return cls.from_mapping(data)
Example #2
Source File: s3connector.py From resolwe with Apache License 2.0 | 6 votes |
def get_hashes(self, url, hash_types): """Get the hash of the given type for the given object.""" resource = self.awss3.Object(self.bucket_name, os.fspath(url)) hashes = dict() try: for hash_type in hash_types: if hash_type in self.hash_propery: prop = self.hash_propery[hash_type] hashes[hash_type] = getattr(resource, prop).strip('"') else: hashes[hash_type] = resource.metadata.get(hash_type) except botocore.exceptions.ClientError as error: if error.response["Error"]["Code"] == "404": return None else: # Something else has gone wrong. raise return hashes
Example #3
Source File: s3connector.py From resolwe with Apache License 2.0 | 6 votes |
def set_hashes(self, url, hashes): """Set the hashes for the given object.""" # Changing metadata on existing objects in S3 is annoyingly hard. # See # https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3.html # under managed copy for example. # If one uses copy_object method proposed by some solutions the e_tag # value on object can (and will) change. That causes error downloading # since hash check fails. url = os.fspath(url) head = self.client.head_object(Bucket=self.bucket_name, Key=url) meta = head["Metadata"] hashes = {k: v for (k, v) in hashes.items() if k not in self.hash_propery} meta.update(hashes) copy_source = { "Bucket": self.bucket_name, "Key": url, } self.client.copy( copy_source, self.bucket_name, url, ExtraArgs={"Metadata": meta, "MetadataDirective": "REPLACE"}, )
Example #4
Source File: genericpath.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' # Some people pass in a list of pathname parts to operate in an OS-agnostic # fashion; don't try to translate in that case as that's an abuse of the # API and they are already doing what they need to be OS-agnostic and so # they most likely won't be using an os.PathLike object in the sublists. if not isinstance(m[0], (list, tuple)): m = tuple(map(os.fspath, m)) s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1 # Are two stat buffers (obtained from stat, fstat or lstat) # describing the same file?
Example #5
Source File: googleconnector.py From resolwe with Apache License 2.0 | 6 votes |
def presigned_url(self, url, expiration=60, force_download=False): """Create a presigned URL. The URL is used to obtain temporary access to the object ar the given URL using only returned URL. :param expiration: expiration time of the link (in seconds), default is one minute. :param force_download: force download. :returns: URL that can be used to access object or None. """ content_disposition = "attachment" if force_download else "inline" query_parameters = {"response-content-disposition": content_disposition} blob = self.bucket.blob(os.fspath(url)) response = blob.generate_signed_url( version="v4", expiration=datetime.timedelta(seconds=expiration), method="GET", virtual_hosted_style=True, query_parameters=query_parameters, ) return response
Example #6
Source File: ntpath.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.""" s = os.fspath(s) try: if isinstance(s, bytes): return s.replace(b'/', b'\\').lower() else: return s.replace('/', '\\').lower() except (TypeError, AttributeError): if not isinstance(s, (bytes, str)): raise TypeError("normcase() argument must be str or bytes, " "not %r" % s.__class__.__name__) from None raise # Return whether a path is absolute. # Trivial in Posix, harder on Windows. # For Windows it is absolute if it starts with a slash or backslash (current # volume), or if a pathname after the volume-letter-and-colon or UNC-resource # starts with a slash or backslash.
Example #7
Source File: posixpath.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" p = os.fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 head, tail = p[:i], p[i:] if head and head != sep*len(head): head = head.rstrip(sep) return head, tail # Split a path in root and extension. # The extension is everything starting at the last dot in the last # pathname component; the root is everything before that. # It is always true that root + ext == p.
Example #8
Source File: __init__.py From python-atomicwrites with MIT License | 6 votes |
def __init__(self, path, mode=DEFAULT_MODE, overwrite=False, **open_kwargs): if 'a' in mode: raise ValueError( 'Appending to an existing file is not supported, because that ' 'would involve an expensive `copy`-operation to a temporary ' 'file. Open the file in normal `w`-mode and copy explicitly ' 'if that\'s what you\'re after.' ) if 'x' in mode: raise ValueError('Use the `overwrite`-parameter instead.') if 'w' not in mode: raise ValueError('AtomicWriters can only be written to.') # Attempt to convert `path` to `str` or `bytes` if fspath is not None: path = fspath(path) self._path = path self._mode = mode self._overwrite = overwrite self._open_kwargs = open_kwargs
Example #9
Source File: configparser.py From chinese-support-redux with GNU General Public License v3.0 | 6 votes |
def read(self, filenames, encoding=None): """Read and parse a filename or an iterable of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify an iterable of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the iterable will be read. A single filename may also be given. Return list of successfully read files. """ if isinstance(filenames, (str, bytes, os.PathLike)): filenames = [filenames] read_ok = [] for filename in filenames: try: with open(filename, encoding=encoding) as fp: self._read(fp, filename) except OSError: continue if isinstance(filename, os.PathLike): filename = os.fspath(filename) read_ok.append(filename) return read_ok
Example #10
Source File: ntpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def splitext(p): p = os.fspath(p) if isinstance(p, bytes): return genericpath._splitext(p, b'\\', b'/', b'.') else: return genericpath._splitext(p, '\\', '/', '.')
Example #11
Source File: compat.py From pytest with MIT License | 5 votes |
def fspath(p): """os.fspath replacement, useful to point out when we should replace it by the real function once we drop py35. """ return str(p)
Example #12
Source File: posixpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def dirname(p): """Returns the directory component of a pathname""" p = os.fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 head = p[:i] if head and head != sep*len(head): head = head.rstrip(sep) return head # Is a path a symbolic link? # This will always return false on systems where os.lstat doesn't exist.
Example #13
Source File: py2index.py From resolvelib with ISC License | 5 votes |
def get_output_path(path: pathlib.Path, overwrite: bool) -> pathlib.Path: if path.suffix != ".json": path = path.with_name(path.name + ".json") if path.is_file() and not overwrite: raise FileExistsError(os.fspath(path)) path.parent.mkdir(parents=True, exist_ok=True) return path
Example #14
Source File: __init__.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def to_filehandle(fname, flag='rU', return_opened=False, encoding=None): """ *fname* can be an `os.PathLike` or a file handle. Support for gzipped files is automatic, if the filename ends in .gz. *flag* is a read/write flag for :func:`file` """ if isinstance(fname, getattr(os, "PathLike", ())): fname = os.fspath(fname) if isinstance(fname, str): if fname.endswith('.gz'): # get rid of 'U' in flag for gzipped files. flag = flag.replace('U', '') fh = gzip.open(fname, flag) elif fname.endswith('.bz2'): # python may not be complied with bz2 support, # bury import until we need it import bz2 # get rid of 'U' in flag for bz2 files flag = flag.replace('U', '') fh = bz2.BZ2File(fname, flag) else: fh = open(fname, flag, encoding=encoding) opened = True elif hasattr(fname, 'seek'): fh = fname opened = False else: raise ValueError('fname must be a PathLike or file handle') if return_opened: return fh, opened return fh
Example #15
Source File: posixpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def relpath(path, start=None): """Return a relative version of a path""" if not path: raise ValueError("no path specified") path = os.fspath(path) if isinstance(path, bytes): curdir = b'.' sep = b'/' pardir = b'..' else: curdir = '.' sep = '/' pardir = '..' if start is None: start = curdir else: start = os.fspath(start) try: start_list = [x for x in abspath(start).split(sep) if x] path_list = [x for x in abspath(path).split(sep) if x] # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) except (TypeError, AttributeError, BytesWarning, DeprecationWarning): genericpath._check_arg_types('relpath', path, start) raise # Return the longest common sub-path of the sequence of paths given as input. # The paths are not normalized before comparing them (this is the # responsibility of the caller). Any trailing separator is stripped from the # returned path.
Example #16
Source File: posixpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def realpath(filename): """Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.""" filename = os.fspath(filename) path, ok = _joinrealpath(filename[:0], filename, {}) return abspath(path) # Join two paths, normalizing and eliminating any symbolic links # encountered in the second path.
Example #17
Source File: posixpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def abspath(path): """Return an absolute path.""" path = os.fspath(path) if not isabs(path): if isinstance(path, bytes): cwd = os.getcwdb() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path) # Return a canonical path (i.e. the absolute location of a file on the # filesystem).
Example #18
Source File: posixpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def commonpath(paths): """Given a sequence of path names, returns the longest common sub-path.""" if not paths: raise ValueError('commonpath() arg is an empty sequence') paths = tuple(map(os.fspath, paths)) if isinstance(paths[0], bytes): sep = b'/' curdir = b'.' else: sep = '/' curdir = '.' try: split_paths = [path.split(sep) for path in paths] try: isabs, = set(p[:1] == sep for p in paths) except ValueError: raise ValueError("Can't mix absolute and relative paths") from None split_paths = [[c for c in s if c and c != curdir] for s in split_paths] s1 = min(split_paths) s2 = max(split_paths) common = s1 for i, c in enumerate(s1): if c != s2[i]: common = s1[:i] break prefix = sep if isabs else sep[:0] return prefix + sep.join(common) except (TypeError, AttributeError): genericpath._check_arg_types('commonpath', *paths) raise
Example #19
Source File: compat.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def fspath(path): """ Return the string representation of the path. If str or bytes is passed in, it is returned unchanged. This code comes from PEP 519, modified to support earlier versions of python. This is required for python < 3.6. """ if isinstance(path, (six.text_type, six.binary_type)): return path # Work from the object's type to match method resolution of other magic # methods. path_type = type(path) try: return path_type.__fspath__(path) except AttributeError: if hasattr(path_type, '__fspath__'): raise try: import pathlib except ImportError: pass else: if isinstance(path, pathlib.PurePath): return six.text_type(path) raise TypeError("expected str, bytes or os.PathLike object, not " + path_type.__name__) # This is from python 3.5 stdlib (hence lacks PEP 519 changes) # This was introduced into python 3.2, so python < 3.2 does not have this # Effectively, this is only required for python 2.6 and 2.7, and can be removed # once support for them is dropped
Example #20
Source File: compilerPool.py From fontgoggles with Apache License 2.0 | 5 votes |
def compileUFOToPath(ufoPath, ttPath, outputWriter): pool = getCompilerPool() func = "fontgoggles.compile.ufoCompiler.compileUFOToPath" args = [ os.fspath(ufoPath), os.fspath(ttPath), ] return await pool.callFunction(func, args, outputWriter)
Example #21
Source File: ntpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def ismount(path): """Test whether a path is a mount point (a drive root, the root of a share, or a mounted volume)""" path = os.fspath(path) seps = _get_bothseps(path) path = abspath(path) root, rest = splitdrive(path) if root and root[0] in seps: return (not rest) or (rest in seps) if rest in seps: return True if _getvolumepathname: return path.rstrip(seps) == _getvolumepathname(path).rstrip(seps) else: return False # Expand paths beginning with '~' or '~user'. # '~' means $HOME; '~user' means that user's home directory. # If the path doesn't begin with '~', or if the user or $HOME is unknown, # the path is returned unchanged (leaving error reporting to whatever # function is called with the expanded path as argument). # See also module 'glob' for expansion of *, ? and [...] in pathnames. # (A function should also be defined to do full *sh-style environment # variable expansion.)
Example #22
Source File: fontList.py From fontgoggles with Apache License 2.0 | 5 votes |
def revealInFinder_(self, sender): fontPath = os.fspath(self.vanillaWrapper().fontPath) workspace = AppKit.NSWorkspace.sharedWorkspace() workspace.selectFile_inFileViewerRootedAtPath_(fontPath, "")
Example #23
Source File: compilerPool.py From fontgoggles with Apache License 2.0 | 5 votes |
def compileDSToPath(dsPath, ttFolder, ttPath, outputWriter): pool = getCompilerPool() func = "fontgoggles.compile.dsCompiler.compileDSToPath" args = [ os.fspath(dsPath), os.fspath(ttFolder), os.fspath(ttPath), ] return await pool.callFunction(func, args, outputWriter)
Example #24
Source File: ntpath.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def isabs(s): """Test whether a path is absolute""" s = os.fspath(s) s = splitdrive(s)[1] return len(s) > 0 and s[0] in _get_bothseps(s) # Join two (or more) paths.
Example #25
Source File: static.py From quart with MIT License | 5 votes |
def jinja_loader(self) -> Optional[FileSystemLoader]: if self.template_folder is not None: return FileSystemLoader(os.fspath(self.root_path / self.template_folder)) else: return None
Example #26
Source File: shutil.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", "gztar", "bztar", or "xztar". Or any other registered format. If not provided, unpack_archive will use the filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() extract_dir = os.fspath(extract_dir) filename = os.fspath(filename) if format is not None: try: format_info = _UNPACK_FORMATS[format] except KeyError: raise ValueError("Unknown unpack format '{0}'".format(format)) from None func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) else: # we need to look at the registered unpackers supported extensions format = _find_unpack_format(filename) if format is None: raise ReadError("Unknown archive format '{0}'".format(filename)) func = _UNPACK_FORMATS[format][1] kwargs = dict(_UNPACK_FORMATS[format][2]) func(filename, extract_dir, **kwargs)
Example #27
Source File: files.py From aiologger with MIT License | 5 votes |
def __init__( self, filename: str, mode: str = "a", encoding: str = None, *, loop: Optional[AbstractEventLoop] = None, ) -> None: super().__init__(loop=loop) filename = os.fspath(filename) self.absolute_file_path = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.stream: AsyncTextIOWrapper = None self._initialization_lock = None
Example #28
Source File: __init__.py From pipenv with MIT License | 5 votes |
def _parse_args(cls, args): # This is useful when you don't want to create an instance, just # canonicalize some constructor arguments. parts = [] for a in args: if isinstance(a, PurePath): parts += a._parts else: if sys.version_info >= (3, 6): a = os.fspath(a) else: # duck typing for older Python versions if hasattr(a, "__fspath__"): a = a.__fspath__() if isinstance(a, str): # Force-cast str subclasses to str (issue #21127) parts.append(str(a)) # also handle unicode for PY2 (six.text_type = unicode) elif six.PY2 and isinstance(a, six.text_type): # cast to str using filesystem encoding # note: in rare circumstances, on Python < 3.2, # getfilesystemencoding can return None, in that # case fall back to ascii parts.append(a.encode( sys.getfilesystemencoding() or "ascii")) else: raise TypeError( "argument should be a str object or an os.PathLike " "object returning str, not %r" % type(a)) return cls._flavour.parse_parts(parts)
Example #29
Source File: decoder.py From pipenv with MIT License | 5 votes |
def _getpath(p): if (3, 6) <= sys.version_info: import os return os.fspath(p) if _detect_pathlib_path(p): return str(p) return p
Example #30
Source File: _compat.py From pipenv with MIT License | 5 votes |
def fspath(path): if hasattr(path, "__fspath__"): return path.__fspath__() # Python 3.5 doesn't have __fspath__ yet, use str. if PurePath is not None and isinstance(path, PurePath): return str(path) return path