本文整理匯總了Python中os.fsdecode方法的典型用法代碼示例。如果您正苦於以下問題:Python os.fsdecode方法的具體用法?Python os.fsdecode怎麽用?Python os.fsdecode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os
的用法示例。
在下文中一共展示了os.fsdecode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_soname
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def _get_soname(f):
if not f:
return None
try:
proc = subprocess.Popen(("/usr/ccs/bin/dump", "-Lpv", f),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
except OSError: # E.g. command not found
return None
with proc:
data = proc.stdout.read()
res = re.search(br'\[.*\]\sSONAME\s+([^\s]+)', data)
if not res:
return None
return os.fsdecode(res.group(1))
示例2: find_library
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def find_library(name):
ename = re.escape(name)
expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
expr = os.fsencode(expr)
try:
proc = subprocess.Popen(('/sbin/ldconfig', '-r'),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
except OSError: # E.g. command not found
data = b''
else:
with proc:
data = proc.stdout.read()
res = re.findall(expr, data)
if not res:
return _get_soname(_findLib_gcc(name))
res.sort(key=_num_version)
return os.fsdecode(res[-1])
示例3: _findLib_ld
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def _findLib_ld(name):
# See issue #9998 for why this is needed
expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
cmd = ['ld', '-t']
libpath = os.environ.get('LD_LIBRARY_PATH')
if libpath:
for d in libpath.split(':'):
cmd.extend(['-L', d])
cmd.extend(['-o', os.devnull, '-l%s' % name])
result = None
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
out, _ = p.communicate()
res = re.search(expr, os.fsdecode(out))
if res:
result = res.group(0)
except Exception as e:
pass # result will be None
return result
示例4: filename_decode
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def filename_decode(filename):
"""
Decode filename used by HDF5 library.
Due to how HDF5 handles filenames on different systems, this should be
called on any filenames passed from the HDF5 library. See the documentation
on filenames in h5py for more information.
"""
if sys.platform == "win32":
if isinstance(filename, six.binary_type):
return filename.decode(WINDOWS_ENCODING, "strict")
elif isinstance(filename, six.text_type):
return filename
else:
raise TypeError("expect bytes or str, not %s" % type(filename).__name__)
return fsdecode(filename)
示例5: fc_match
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def fc_match(pattern, fontext):
fontexts = get_fontext_synonyms(fontext)
ext = "." + fontext
try:
pipe = subprocess.Popen(
['fc-match', '-s', '--format=%{file}\\n', pattern],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output = pipe.communicate()[0]
except OSError:
return None
# The bulk of the output from fc-list is ascii, so we keep the
# result in bytes and parse it as bytes, until we extract the
# filename, which is in sys.filesystemencoding().
if pipe.returncode == 0:
for fname in map(os.fsdecode, output.split(b'\n')):
if os.path.splitext(fname)[1][1:] in fontexts:
return fname
return None
示例6: test_undecodable_filename
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def test_undecodable_filename(self):
enc = sys.getfilesystemencoding()
filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
with open(os.path.join(self.tempdir, filename), 'wb') as f:
f.write(support.TESTFN_UNDECODABLE)
response = self.request(self.tempdir_name + '/')
if sys.platform == 'darwin':
# On Mac OS the HFS+ filesystem replaces bytes that aren't valid
# UTF-8 into a percent-encoded value.
for name in os.listdir(self.tempdir):
if name != 'test': # Ignore a filename created in setUp().
filename = name
break
body = self.check_status_and_reason(response, HTTPStatus.OK)
quotedname = urllib.parse.quote(filename, errors='surrogatepass')
self.assertIn(('href="%s"' % quotedname)
.encode(enc, 'surrogateescape'), body)
self.assertIn(('>%s<' % html.escape(filename))
.encode(enc, 'surrogateescape'), body)
response = self.request(self.tempdir_name + '/' + quotedname)
self.check_status_and_reason(response, HTTPStatus.OK,
data=support.TESTFN_UNDECODABLE)
示例7: test_non_ascii
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def test_non_ascii(self):
# Mac OS X denies the creation of a file with an invalid UTF-8 name.
# Windows allows to create a name with an arbitrary bytes name, but
# Python cannot a undecodable bytes argument to a subprocess.
if (support.TESTFN_UNDECODABLE
and sys.platform not in ('win32', 'darwin')):
name = os.fsdecode(support.TESTFN_UNDECODABLE)
elif support.TESTFN_NONASCII:
name = support.TESTFN_NONASCII
else:
self.skipTest("need support.TESTFN_NONASCII")
# Issue #16218
source = 'print(ascii(__file__))\n'
script_name = _make_test_script(os.curdir, name, source)
self.addCleanup(support.unlink, script_name)
rc, stdout, stderr = assert_python_ok(script_name)
self.assertEqual(
ascii(script_name),
stdout.rstrip().decode('ascii'),
'stdout=%r stderr=%r' % (stdout, stderr))
self.assertEqual(0, rc)
示例8: __init__
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def __init__(self, path):
if not isinstance(path, str):
import os
path = os.fsdecode(path)
if not path:
raise ZipImportError('archive path is empty', path=path)
if alt_path_sep:
path = path.replace(alt_path_sep, path_sep)
prefix = []
while True:
try:
st = _bootstrap_external._path_stat(path)
except (OSError, ValueError):
# On Windows a ValueError is raised for too long paths.
# Back up one path element.
dirname, basename = _bootstrap_external._path_split(path)
if dirname == path:
raise ZipImportError('not a Zip file', path=path)
path = dirname
prefix.append(basename)
else:
# it exists
if (st.st_mode & 0o170000) != 0o100000: # stat.S_ISREG
# it's a not file
raise ZipImportError('not a Zip file', path=path)
break
try:
files = _zip_directory_cache[path]
except KeyError:
files = _read_directory(path)
_zip_directory_cache[path] = files
self._files = files
self.archive = path
# a prefix directory following the ZIP file path.
self.prefix = _bootstrap_external._path_join(*prefix[::-1])
if self.prefix:
self.prefix += path_sep
示例9: fsdecode
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def fsdecode(filename):
if isinstance(filename, text_type):
return filename
elif isinstance(filename, bytes):
return filename.decode(_fsencoding, _fserrors)
else:
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
示例10: path
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def path( node, prop ):
node = node.str( prop )
if node[:1] != b'/':
raise RuntimeError( "Malformed device tree node: %s" % node )
return dt_root / os.fsdecode( node[1:] )
示例11: _findLib_gcc
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def _findLib_gcc(name):
# Run GCC's linker with the -t (aka --trace) option and examine the
# library name it prints out. The GCC command will fail because we
# haven't supplied a proper program with main(), but that does not
# matter.
expr = os.fsencode(r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name))
c_compiler = shutil.which('gcc')
if not c_compiler:
c_compiler = shutil.which('cc')
if not c_compiler:
# No C compiler available, give up
return None
temp = tempfile.NamedTemporaryFile()
try:
args = [c_compiler, '-Wl,-t', '-o', temp.name, '-l' + name]
env = dict(os.environ)
env['LC_ALL'] = 'C'
env['LANG'] = 'C'
try:
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env)
except OSError: # E.g. bad executable
return None
with proc:
trace = proc.stdout.read()
finally:
try:
temp.close()
except FileNotFoundError:
# Raised if the file was already removed, which is the normal
# behaviour of GCC if linking fails
pass
res = re.search(expr, trace)
if not res:
return None
return os.fsdecode(res.group(0))
示例12: _findLib_crle
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def _findLib_crle(name, is64):
if not os.path.exists('/usr/bin/crle'):
return None
env = dict(os.environ)
env['LC_ALL'] = 'C'
if is64:
args = ('/usr/bin/crle', '-64')
else:
args = ('/usr/bin/crle',)
paths = None
try:
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
except OSError: # E.g. bad executable
return None
with proc:
for line in proc.stdout:
line = line.strip()
if line.startswith(b'Default Library Path (ELF):'):
paths = os.fsdecode(line).split()[4]
if not paths:
return None
for dir in paths.split(":"):
libfile = os.path.join(dir, "lib%s.so" % name)
if os.path.exists(libfile):
return libfile
return None
示例13: __hashLink
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def __hashLink(path):
m = hashlib.sha1()
try:
m.update(os.fsencode(os.readlink(os.fsdecode(path))))
except OSError as e:
logging.getLogger(__name__).warning("Cannot hash link: %s", str(e))
return m.digest()
示例14: __init__
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def __init__(self, directory: ty.Union[utils.path_t, int], *,
chunk_size: int = default_chunk_size,
follow_symlinks: bool = False,
patterns: match_spec_t[ty.AnyStr] = None,
period_special: bool = True,
recursive: bool = False):
self.follow_symlinks = follow_symlinks
directory = utils.convert_path(directory) if not isinstance(directory, int) else directory
# Create file scanner from parameters
self.scanner = filescanner.walk(
directory, patterns, follow_symlinks=follow_symlinks,
period_special=period_special, recursive=recursive
)
# Figure out the absolute path of the directory added
self.abspath = None
if not isinstance(directory, int):
self.abspath = os.path.abspath(utils.convert_path(directory))
# Figure out basename of the containing directory
# (normpath is an acceptable approximation here)
basename = "_" # type: ty.Union[str, bytes]
if not isinstance(directory, int):
basename = os.fsdecode(os.path.basename(os.path.normpath(directory)))
super().__init__(os.fsdecode(basename), chunk_size=chunk_size)
示例15: _body
# 需要導入模塊: import os [as 別名]
# 或者: from os import fsdecode [as 別名]
def _body(self):
"""Streams the contents of the selected directory as binary chunks."""
try:
for type, path, relpath, name, parentfd in self.scanner:
relpath_unicode = os.fsdecode(relpath).replace(os.path.sep, "/")
short_path = self.name + (("/" + relpath_unicode) if relpath_unicode != "." else "")
if type is filescanner.FSNodeType.FILE:
try:
# Only regular files and directories can be uploaded
if parentfd is not None:
stat_data = os.stat(name, dir_fd=parentfd, follow_symlinks=self.follow_symlinks)
else:
stat_data = os.stat(path, follow_symlinks=self.follow_symlinks)
if not stat.S_ISREG(stat_data.st_mode):
continue
absolute_path = None # type: ty.Optional[str]
if self.abspath is not None:
absolute_path = os.fsdecode(os.path.join(self.abspath, relpath))
if parentfd is not None:
f_path_or_desc = os.open(name, os.O_RDONLY | os.O_CLOEXEC, dir_fd=parentfd)
else:
f_path_or_desc = path
# Stream file to client
with open(f_path_or_desc, "rb") as file:
yield from self._gen_file(short_path, absolute_path, file)
except OSError as e:
print(e)
# File might have disappeared between `os.walk()` and `open()`
pass
elif type is filescanner.FSNodeType.DIRECTORY:
# Generate directory as special empty file
yield from self._gen_file(short_path, content_type="application/x-directory")
yield from self._gen_end()
finally:
self.scanner.close()