本文整理汇总了Python中os.fsencode方法的典型用法代码示例。如果您正苦于以下问题:Python os.fsencode方法的具体用法?Python os.fsencode怎么用?Python os.fsencode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.fsencode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_library
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [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])
示例2: _sanitize_params
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def _sanitize_params(prefix, suffix, dir):
"""Common parameter processing for most APIs in this module."""
output_type = _infer_return_type(prefix, suffix, dir)
if suffix is None:
suffix = output_type()
if prefix is None:
if output_type is str:
prefix = template
else:
prefix = _os.fsencode(template)
if dir is None:
if output_type is str:
dir = gettempdir()
else:
dir = gettempdirb()
return prefix, suffix, dir, output_type
示例3: expanduser
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def expanduser(path):
"""Expand ~ and ~user constructions. If user or $HOME is unknown,
do nothing."""
if isinstance(path, bytes):
tilde = b'~'
else:
tilde = '~'
if not path.startswith(tilde):
return path
sep = _get_sep(path)
i = path.find(sep, 1)
if i < 0:
i = len(path)
if i == 1:
if 'HOME' not in os.environ:
import pwd
userhome = pwd.getpwuid(os.getuid()).pw_dir
else:
userhome = os.environ['HOME']
else:
import pwd
name = path[1:i]
if isinstance(name, bytes):
name = str(name, 'ASCII')
try:
pwent = pwd.getpwnam(name)
except KeyError:
return path
userhome = pwent.pw_dir
if isinstance(path, bytes):
userhome = os.fsencode(userhome)
root = b'/'
else:
root = '/'
userhome = userhome.rstrip(root)
return (userhome + path[i:]) or root
# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged.
示例4: binary_value_or_stdin
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def binary_value_or_stdin(value):
"""
Return fsencoded value or read raw data from stdin if value is None.
"""
if value is None:
reader = io.open(sys.stdin.fileno(), mode='rb', closefd=False)
return reader.read()
elif six.PY3:
return os.fsencode(value)
else:
return value
示例5: test_fspath_fsencode
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def test_fspath_fsencode(self, path1):
from os import fsencode
assert fsencode(path1) == fsencode(path1.strpath)
示例6: fsencode
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def fsencode(filename):
if isinstance(filename, bytes):
return filename
elif isinstance(filename, str):
return filename.encode(sys.getfilesystemencoding())
else:
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
示例7: fsencode
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def fsencode(filename):
if isinstance(filename, bytes):
return filename
elif isinstance(filename, text_type):
return filename.encode(_fsencoding, _fserrors)
else:
raise TypeError("expect bytes or str, not %s" %
type(filename).__name__)
示例8: __bytes__
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def __bytes__(self):
"""Return the bytes representation of the path. This is only
recommended to use under Unix."""
if sys.version_info < (3, 2):
raise NotImplementedError("needs Python 3.2 or later")
return os.fsencode(str(self))
示例9: _findLib_gcc
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [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))
示例10: _findSoname_ldconfig
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def _findSoname_ldconfig(name):
import struct
if struct.calcsize('l') == 4:
machine = os.uname().machine + '-32'
else:
machine = os.uname().machine + '-64'
mach_map = {
'x86_64-64': 'libc6,x86-64',
'ppc64-64': 'libc6,64bit',
'sparc64-64': 'libc6,64bit',
's390x-64': 'libc6,64bit',
'ia64-64': 'libc6,IA-64',
}
abi_type = mach_map.get(machine, 'libc6')
# XXX assuming GLIBC's ldconfig (with option -p)
regex = r'\s+(lib%s\.[^\s]+)\s+\(%s'
regex = os.fsencode(regex % (re.escape(name), abi_type))
try:
with subprocess.Popen(['/sbin/ldconfig', '-p'],
stdin=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stdout=subprocess.PIPE,
env={'LC_ALL': 'C', 'LANG': 'C'}) as p:
res = re.search(regex, p.stdout.read())
if res:
return os.fsdecode(res.group(1))
except OSError:
pass
示例11: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def __init__(self, basePath=None, ignoreDirs=None):
if basePath:
self.__index = DirHasher.FileIndex(basePath)
else:
self.__index = DirHasher.NullIndex()
if ignoreDirs:
self.__ignoreDirs = DirHasher.IGNORE_DIRS | frozenset(os.fsencode(i) for i in ignoreDirs)
else:
self.__ignoreDirs = DirHasher.IGNORE_DIRS
示例12: __hashLink
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [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()
示例13: __hashDir
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def __hashDir(self, prefix, path=b''):
entries = []
try:
dirEntries = os.listdir(os.path.join(prefix, path if path else b'.'))
except OSError as e:
logging.getLogger(__name__).warning("Cannot list directory: %s", str(e))
dirEntries = []
for f in dirEntries:
e = os.path.join(path, f)
try:
s = os.lstat(os.path.join(prefix, e))
if stat.S_ISDIR(s.st_mode):
# skip useless directories
if f in self.__ignoreDirs: continue
# add training '/' for directores for correct sorting
f = f + os.fsencode(os.path.sep)
else:
# skip useless files
if f in DirHasher.IGNORE_FILES: continue
entries.append((e, f, s))
except OSError as err:
logging.getLogger(__name__).warning("Cannot stat '%s': %s", e, str(err))
entries = sorted(entries, key=lambda x: x[1])
dirList = [
(struct.pack("=L", s.st_mode) + self.__hashEntry(prefix, e, s) + f)
for (e, f, s) in entries
]
dirBlob = b"".join(dirList)
m = hashlib.sha1()
m.update(dirBlob)
return m.digest()
示例14: hashDirectory
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def hashDirectory(self, path):
self.__index.open()
try:
return self.__hashDir(os.fsencode(path))
finally:
self.__index.close()
示例15: hashPath
# 需要导入模块: import os [as 别名]
# 或者: from os import fsencode [as 别名]
def hashPath(self, path):
path = os.fsencode(path)
try:
s = os.lstat(path)
except OSError as err:
logging.getLogger(__name__).warning("Cannot stat '%s': %s", path, str(err))
return b''
self.__index.open()
try:
return self.__hashEntry(path, b'', s)
finally:
self.__index.close()