本文整理汇总了Python中os.path.startswith方法的典型用法代码示例。如果您正苦于以下问题:Python path.startswith方法的具体用法?Python path.startswith怎么用?Python path.startswith使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.path
的用法示例。
在下文中一共展示了path.startswith方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scan
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def scan(self, path, exclude=[]) -> List[str]:
"""Scan path for matching files.
:param path: the path to scan
:param exclude: a list of directories to exclude
:return: a list of sorted filenames
"""
res = []
path = path.rstrip("/").rstrip("\\")
for pat in self.input_patterns:
res.extend(glob.glob(path + os.sep + pat, recursive=True))
res = list(filter(lambda p: os.path.isfile(p), res))
if exclude:
def excluded(path):
for e in exclude:
if path.startswith(e):
return True
return False
res = list(filter(lambda p: not excluded(p), res))
return sorted(res)
示例2: copymode
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def copymode(src, dst, follow_symlinks=True, **kwargs):
"""
Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. Due to the
limitations of Windows, this function only sets/unsets the dst's FILE_ATTRIBUTE_READ_ONLY flag based on what src's
attribute is set to.
If follow_symlinks is 'False', and both src and dst are symbolic links, copymode() will attempt to modify the mode
of dst itself (rather than the file it points to).
This function supports src and dst being either a local or UNC path. A relative path will be resolved based on the
current working directory.
:param src: The src file or directory to copy the read only flag from.
:param dst: The dst file or directory to copy the read only flag to.
:param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
:param kwargs: Common arguments used to build the SMB Session for any UNC paths.
"""
src_mode = stat.S_IMODE(_get_file_stat(src, follow_symlinks, **kwargs).st_mode)
norm_dst = ntpath.normpath(dst)
if norm_dst.startswith('\\\\'):
read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
_set_file_basic_info(dst, follow_symlinks, read_only=read_only, **kwargs)
else:
_local_chmod(dst, src_mode, follow_symlinks)
示例3: put
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def put(self, bucket, object_name):
object_name = urllib.unquote(object_name)
bucket_dir = os.path.abspath(os.path.join(
self.application.directory, bucket))
if not bucket_dir.startswith(self.application.directory) or \
not os.path.isdir(bucket_dir):
raise web.HTTPError(404)
path = self._object_path(bucket, object_name)
if not path.startswith(bucket_dir) or os.path.isdir(path):
raise web.HTTPError(403)
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
object_file = open(path, "w")
object_file.write(self.request.body)
object_file.close()
self.finish()
示例4: get_browser_locale
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def get_browser_locale(self, default="en_US"):
"""从 ``Accept-Language`` 头决定用户的位置.
参考 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
示例5: path_to_url
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def path_to_url(self, path, *, port=None, https=False):
"""Get a URL based on a filename for the localhost webserver.
URLs like about:... and qute:... are handled specially and returned
verbatim.
"""
special_schemes = ['about:', 'qute:', 'chrome:', 'view-source:',
'data:', 'http:', 'https:']
server = self.request.getfixturevalue('server')
server_port = server.port if port is None else port
if any(path.startswith(scheme) for scheme in special_schemes):
path = path.replace('(port)', str(server_port))
return path
else:
return '{}://localhost:{}/{}'.format(
'https' if https else 'http',
server_port,
path if path != '/' else '')
示例6: _is_error_logline
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def _is_error_logline(self, msg):
"""Check if the given LogLine is some kind of error message."""
is_js_error = (msg.category == 'js' and
testutils.pattern_match(pattern='[*] [FAIL] *',
value=msg.message))
# Try to complain about the most common mistake when accidentally
# loading external resources.
is_ddg_load = testutils.pattern_match(
pattern="load status for <* tab_id=* url='*duckduckgo*'>: *",
value=msg.message)
is_log_error = (msg.loglevel > logging.INFO and
not msg.message.startswith("Ignoring world ID") and
not msg.message.startswith(
"Could not initialize QtNetwork SSL support."))
return is_log_error or is_js_error or is_ddg_load
示例7: _init_data
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def _init_data(args: typing.Optional[argparse.Namespace]) -> None:
"""Initialize the location for data."""
typ = QStandardPaths.DataLocation
path = _from_args(typ, args)
if path is None:
if utils.is_windows:
app_data_path = _writable_location(QStandardPaths.AppDataLocation)
path = os.path.join(app_data_path, 'data')
elif sys.platform.startswith('haiku'):
# HaikuOS returns an empty value for AppDataLocation
config_path = _writable_location(QStandardPaths.ConfigLocation)
path = os.path.join(config_path, 'data')
else:
path = _writable_location(typ)
_create(path)
_locations[_Location.data] = path
# system_data
_locations.pop(_Location.system_data, None) # Remove old state
if utils.is_linux:
path = '/usr/share/' + APPNAME
if os.path.exists(path):
_locations[_Location.system_data] = path
示例8: get
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def get(self, bucket, object_name):
object_name = parse.unquote(object_name)
path = self._object_path(bucket, object_name)
if (not path.startswith(self.application.directory) or
not os.path.isfile(path)):
self.set_404()
return
info = os.stat(path)
self.set_header("Content-Type", "application/unknown")
self.set_header("Last-Modified", datetime.datetime.utcfromtimestamp(
info.st_mtime))
object_file = open(path, "rb")
try:
self.finish(object_file.read())
finally:
object_file.close()
示例9: get_browser_locale
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def get_browser_locale(self, default: str = "en_US") -> tornado.locale.Locale:
"""Determines the user's locale from ``Accept-Language`` header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
示例10: selectReceivePath
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def selectReceivePath(self, paths):
""" From a set of source paths, recommend a destination path.
The paths are relative or absolute, in a source Store.
The result will be absolute, suitable for this destination Store.
"""
logger.debug("%s", paths)
if not paths:
path = os.path.basename(self.userPath) + '/Anon'
try:
# Relative paths are preferred
path = [p for p in paths if not p.startswith("/")][0]
except IndexError:
# If no relative path, just use the first path
path = os.path.relpath(list(paths)[0], self.userPath)
return self._fullPath(path)
# Private and subclass methods
示例11: _relativePath
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def _relativePath(self, fullPath):
""" Return fullPath relative to Store directory.
Return fullPath if fullPath is not inside directory.
Return None if fullPath is outside our scope.
"""
if fullPath is None:
return None
assert fullPath.startswith("/"), fullPath
path = os.path.relpath(fullPath, self.userPath)
if not path.startswith("../"):
return path
elif self.ignoreExtraVolumes:
return None
else:
return fullPath
示例12: _flushPartialUploads
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def _flushPartialUploads(self, dryrun):
for upload in self.bucket.list_multipart_uploads():
# logger.debug("Upload: %s", upload.__dict__)
# for part in upload:
# logger.debug(" Part: %s", part.__dict__)
if not upload.key_name.startswith(self.userPath.lstrip("/")):
continue
if self._skipDryRun(logger, 'INFO', dryrun)(
"Delete old partial upload: %s (%d parts)",
upload,
len([part for part in upload]),
):
continue
upload.cancel_upload()
示例13: keep
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def keep(self, diff):
""" Mark this diff (or volume) to be kept in path. """
path = self.extraKeys[diff]
if not path.startswith("/"):
logger.debug("Keeping %s", path)
del self.extraKeys[diff]
return
# Copy into self.userPath, if not there already
keyName = self._keyName(diff.toUUID, diff.fromUUID, path)
newPath = os.path.join(self.userPath, os.path.basename(path))
newName = self._keyName(diff.toUUID, diff.fromUUID, newPath)
if not self._skipDryRun(logger)("Copy %s to %s", keyName, newName):
self.bucket.copy_key(newName, self.bucket.name, keyName)
示例14: get_browser_locale
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def get_browser_locale(self, default="en_US"):
"""Determines the user's locale from ``Accept-Language`` header.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
"""
if "Accept-Language" in self.request.headers:
languages = self.request.headers["Accept-Language"].split(",")
locales = []
for language in languages:
parts = language.strip().split(";")
if len(parts) > 1 and parts[1].startswith("q="):
try:
score = float(parts[1][2:])
except (ValueError, TypeError):
score = 0.0
else:
score = 1.0
locales.append((parts[0], score))
if locales:
locales.sort(key=lambda pair: pair[1], reverse=True)
codes = [l[0] for l in locales]
return locale.get(*codes)
return locale.get(default)
示例15: copystat
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import startswith [as 别名]
def copystat(src, dst, follow_symlinks=True, **kwargs):
"""
Copy the read only attribute, last access time, and last modification time from src to dst. The file contents,
owner, and group are unaffected.
If follow_symlinks is 'False' and src and dst both refer to symbolic links, copystat() will operate on the
symbolic links themselves rather than the files the symbolic links refer to.
:param src: The src file or directory to copy the read only flag from.
:param dst: The dst file or directory to copy the read only flag to.
:param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
:param kwargs: Common arguments used to build the SMB Session for any UNC paths.
"""
src_stat = _get_file_stat(src, follow_symlinks, **kwargs)
src_mode = stat.S_IMODE(src_stat.st_mode)
# *_ns was only added in Python 3, fallback to a manual calculation from seconds since EPOCH.
atime_ns = getattr(src_stat, 'st_atime_ns', src_stat.st_atime * 1000000000)
mtime_ns = getattr(src_stat, 'st_mtime_ns', src_stat.st_mtime * 1000000000)
norm_dst = ntpath.normpath(dst)
if norm_dst.startswith('\\\\'):
read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
_set_file_basic_info(dst, follow_symlinks, read_only=read_only, atime_ns=atime_ns, mtime_ns=mtime_ns, **kwargs)
else:
if not follow_symlinks and sys.version_info[0] < 3:
# Python 2 always follows symlinks and does not have a kwarg to override, we can only just fail here.
raise NotImplementedError("utime: follow_symlinks unavailable on this platform")
_local_chmod(dst, src_mode, follow_symlinks)
if sys.version_info[0] < 3:
os.utime(dst, (atime_ns / 1000000000, mtime_ns / 1000000000))
else:
os.utime(dst, ns=(atime_ns, mtime_ns), follow_symlinks=follow_symlinks)