本文整理汇总了Python中pathlib.PosixPath方法的典型用法代码示例。如果您正苦于以下问题:Python pathlib.PosixPath方法的具体用法?Python pathlib.PosixPath怎么用?Python pathlib.PosixPath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pathlib
的用法示例。
在下文中一共展示了pathlib.PosixPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: infer_settings
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def infer_settings(opt_root, opt_pattern="**/optimizer.py"):
opt_root = PosixPath(opt_root)
assert opt_root.is_dir(), "Opt root directory doesn't exist: %s" % opt_root
assert opt_root.is_absolute(), "Only absolute path should have even gotten this far."
# Always sort for reproducibility
source_files = sorted(opt_root.glob(opt_pattern))
source_files = [ss.relative_to(opt_root) for ss in source_files]
settings = {_cleanup(str(ss.parent)): [str(ss), {}] for ss in source_files}
assert all(joinable(kk) for kk in settings), "Something went wrong in name sanitization."
assert len(settings) == len(source_files), "Name collision after sanitization of %s" % repr(source_files)
assert len(set(CONFIG.keys()) & set(settings.keys())) == 0, "Name collision with builtin optimizers."
return settings
示例2: is_7zfile
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def is_7zfile(file: Union[BinaryIO, str, pathlib.Path]) -> bool:
"""Quickly see if a file is a 7Z file by checking the magic number.
The file argument may be a filename or file-like object too.
"""
result = False
try:
if isinstance(file, io.IOBase) and hasattr(file, "read"):
result = SevenZipFile._check_7zfile(file) # type: ignore # noqa
elif isinstance(file, str):
with open(file, 'rb') as fp:
result = SevenZipFile._check_7zfile(fp)
elif isinstance(file, pathlib.Path) or isinstance(file, pathlib.PosixPath) or \
isinstance(file, pathlib.WindowsPath):
with file.open(mode='rb') as fp: # type: ignore # noqa
result = SevenZipFile._check_7zfile(fp)
else:
raise TypeError('invalid type: file should be str, pathlib.Path or BinaryIO, but {}'.format(type(file)))
except OSError:
pass
return result
示例3: _inject_api_endpoint_to_app
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def _inject_api_endpoint_to_app():
'''
Allows for changing API URL that web app is sending requests to.
Web app expects API URL to be specified in `config.json`.
The file must not exist, it will be created automatically if needed.
'''
try:
web_app_json_config_path = PosixPath(__file__).parent / 'dist/static/config.json'
data = {
'apiPath': 'http://{}:{}/{}'.format(
API.URL_HOSTNAME,
API_SERVER.PORT,
API.URL_PREFIX),
'version': tensorhive.__version__,
'apiVersion': API.VERSION
}
# Overwrite current file content/create file if it does not exist
with open(str(web_app_json_config_path), 'w') as json_file:
json.dump(data, json_file)
except IOError as e:
log.error('Could inject API endpoint URL, reason: ' + str(e))
except Exception as e:
log.critical('Unknown error: ' + str(e))
else:
log.debug('API URL injected successfully: {}'.format(data))
示例4: __init__
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def __init__(self):
super().__init__()
self.infrastructure_manager = InfrastructureManager(SSH.AVAILABLE_NODES)
self.dedicated_ssh_key = ssh.init_ssh_key(PosixPath(SSH.KEY_FILE).expanduser())
if not SSH.AVAILABLE_NODES:
log.error('[!] Empty ssh configuration. Please check {}'.format(SSH.HOSTS_CONFIG_FILE))
raise ConfigurationException
manager_ssh_key_path = SSH.KEY_FILE
if SSH.TEST_ON_STARTUP:
manager_ssh_key_path = self.test_ssh()
self.connection_manager = SSHConnectionManager(config=SSH.AVAILABLE_NODES, ssh_key_path=manager_ssh_key_path)
self.service_manager = None
示例5: lock
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def lock(path: pathlib.PosixPath):
"""Creates a lock file,
a file protected from beeing used by other processes.
(The lock file isn't the same as the file of the passed path.)
Args:
path (pathlib.PosixPath): path to the file
"""
path = path.with_suffix('.lock')
if not path.exists():
path.touch()
with path.open("r+") as lock_file:
try:
fcntl.lockf(lock_file.fileno(), fcntl.LOCK_EX)
yield lock_file
finally:
fcntl.lockf(lock_file.fileno(), fcntl.LOCK_UN)
示例6: test_prepare_api_response
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def test_prepare_api_response(new_cluster):
integration = cinder_integration.CinderIntegration.find_one(
new_cluster.model_id
)
integration.config = "config"
integration.keyrings["images.keyring"] = "[client.images]\n\tkey = 111"
integration.keyrings["vols.keyring"] = "[client.vols]\n\tkey = 22"
root_path = pathlib.PosixPath(pytest.faux.gen_alphanumeric())
response = integration.prepare_api_response(str(root_path))
assert str(root_path.joinpath("ceph.conf")) in response
assert str(root_path.joinpath("images.keyring")) in response
assert str(root_path.joinpath("vols.keyring")) in response
assert len(response) == 3
assert response[str(root_path.joinpath("images.keyring"))] == \
integration.keyrings["images.keyring"]
assert response[str(root_path.joinpath("vols.keyring"))] == \
integration.keyrings["vols.keyring"]
assert "[client.images]" in response[str(root_path.joinpath("ceph.conf"))]
assert "[client.vols]" in response[str(root_path.joinpath("ceph.conf"))]
示例7: _parse_s3url
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def _parse_s3url(cls, s3url: Optional[str] = None):
if s3url is None:
return "", ()
if not s3url.startswith("s3://"):
raise ValueError(
"s3url must be formated as 's3://<bucket_name>/path/to/object'"
)
r = urlparse(s3url)
assert r.scheme == "s3"
key = r.path.lstrip("/") # remove the leading /
parts = PosixPath(key).parts
return r.netloc, parts
示例8: _make_child
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def _make_child(self, args: Iterable[str]):
if not self.bucket:
bucket, *rest_args = args
bucket = bucket.lstrip("/")
bucket, *rest_parts = PosixPath(bucket).parts
return self.with_bucket(bucket)._make_child(rest_parts + rest_args)
parts = [p for p in self._key_parts]
for item in args:
if not isinstance(item, str):
raise ValueError("child must be string")
item = item.lstrip("/") # remove leading '/'
if not item:
raise ValueError("child must not be empty")
for p in PosixPath(item).parts:
parts.append(p)
return self._create(self._client, self.bucket, tuple(parts))
示例9: test_pathlib
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def test_pathlib(app):
assert isinstance(app.config["STORE_PATH"], PosixPath)
assert isinstance(app.config["JSON_PATH"], PosixPath)
assert isinstance(app.config["CACHE_PATH"], PosixPath)
assert app.config["STORE_PATH"].is_dir()
assert app.config["JSON_PATH"].is_dir()
assert app.config["CACHE_PATH"].is_dir()
示例10: converted_path
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def converted_path(self, path):
if self.props.is_windows():
return str(PureWindowsPath(path))
else:
return str(PosixPath(path))
示例11: test_concrete_class
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def test_concrete_class(self):
p = self.cls('a')
self.assertIs(type(p),
pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath)
示例12: test_unsupported_flavour
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def test_unsupported_flavour(self):
if os.name == 'nt':
self.assertRaises(NotImplementedError, pathlib.PosixPath)
else:
self.assertRaises(NotImplementedError, pathlib.WindowsPath)
示例13: getFullPath
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def getFullPath(self, name: str = "") -> str:
path = PosixPath(self.name)
if name != "":
path /= name
path = str(path)
if self.parent is None:
return path
else:
return self.parent.getFullPath(path)
示例14: py_secure_filename
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def py_secure_filename(filename: str) -> str:
"""Method to clean up provided filenames to be safe, relative paths
This function removes leading slashes, control characters, '..' and '.' in directories, and replaces \\/:*"<>|?
with underscores.
Args:
filename: Filename to sanitize
Returns:
str
"""
# Completely remove control characters
safe_filename = "".join(c for c in filename if unicodedata.category(c)[0] != "C")
# Remove leading slash if attempting an absolute path
if safe_filename[0] == "/":
safe_filename = safe_filename[1:]
# Remove ../ or ./ paths (should only be relative names from the repo root)
filename_parts = PosixPath(safe_filename).parts
relative_filename_parts = [p for p in filename_parts if p not in ['..', '.']]
# Replace invalid characters with underscores
invalid_char_map = {ord(ch): '_' for ch in '\\/:*"<>|?'}
safe_parts = [part.translate(invalid_char_map).strip() for part in relative_filename_parts]
safe_filename = "/".join(safe_parts)
if safe_filename != filename:
logger.info(f"Renaming unsafe filename `{filename}` to `{safe_filename}`")
return safe_filename
示例15: logfile
# 需要导入模块: import pathlib [as 别名]
# 或者: from pathlib import PosixPath [as 别名]
def logfile():
path = pathlib.PosixPath('.rfm_unittest.log')
yield path
with suppress(FileNotFoundError):
path.unlink()