pathops¶
pathlib-like interface for local and ops.Container filesystem paths.
The pathops charm library provides:
PathProtocol: defines the interface of methods common to both local and container paths. Use this to type annotate code designed to work on both Kubernetes and machine charms.ContainerPath: the concrete implementation of the interface for remote paths in the workload container of Kubernetes charms. Operations are implemented using the Pebble file API.LocalPath: the concrete implementation of the interface for local paths, which includes both machine charms and the charm container of Kubernetes charms. Inherits frompathlib.PosixPathand extends the signature of some methods.Top-level helper functions such as
ensure_contents, which operate on both container and local paths.
ContainerPath methods that interact with the remote filesystem will raise a
PebbleConnectionError if the workload container isn’t reachable.
Methods designed to work with both local and container paths may handle this error internally,
or they may leave handling connection errors to the caller, documenting this if so.
- class ContainerPath(*parts: str | os.PathLike[str], container: ops.Container)¶
Bases:
objectImplementation of
PathProtocolfor Pebble-based workload containers.The following examples are all equivalent:
container = self.unit.get_container('c') ContainerPath('/foo', container=container) ContainerPath('/', 'foo', container=container) ContainerPath(pathlib.PurePath('/foo'), container=container) ContainerPath(pathlib.PurePath('/'), 'foo', container=container)
strfollows thepathlibconvention and returns the string representation of the path.ContainerPathreturn the string representation of the path in the remote filesystem. The string representation is suitable for use with system calls (on the correct local or remote system) and Pebble layers.Comparison methods compare by path. A
ContainerPathis only comparable to another object if it is also aContainerPathon the sameops.Container. If this is not the case, then equality isFalseand other comparisons areNotImplemented.- Parameters:
*parts – components of the path, like
pathlib.Pathconstructor.container – used to communicate with the workload container. Required. Must be provided as a keyword argument.
- Raises:
RelativePathError – If instantiated with a relative path.
- __truediv__(key: str | os.PathLike[str]) Self¶
Return a new
ContainerPathwith the same container and the joined path.The joined path is equivalent to
str(self) / pathlib.PurePath(key).Warning
__rtruediv__is not supported, asContainerPathonly supports absolute paths. You likely wouldn’t want to provide an absolute path as the right-hand operand, because the absolute path would completely replace the left-hand path.
- exists() bool¶
Whether this path exists.
Will follow symlinks to determine if the symlink target exists. This means that this method will return
Falsefor a broken symlink.- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- glob(pattern: str | os.PathLike[str]) Generator[Self]¶
Iterate over this directory and yield all paths matching the provided pattern.
For example,
path.glob('*.txt'),path.glob('*/foo.txt').Warning
Recursive matching using the
'**'pattern is not supported.- Parameters:
pattern – The pattern must be relative, meaning it cannot begin with
'/'. Matching is case-sensitive.- Returns:
A generator yielding
ContainerPathobjects, corresponding to those of its children which match the pattern. If this path is not a directory, there will be no matches.- Raises:
FileNotFoundError – If this path does not exist.
NotImplementedError – If pattern is an absolute path or it uses the
'**'pattern.PermissionError – If the remote user does not have appropriate permissions.
ValueError – If the pattern is invalid.
PebbleConnectionError – If the remote container cannot be reached.
- group() str¶
Return the group name of the file.
- Raises:
FileNotFoundError – If the path does not exist.
PebbleConnectionError – If the remote container cannot be reached.
- is_absolute() bool¶
Return whether the path is absolute (has a root), which is always the case.
Always
True, since initialising aContainerPathwith a non-absolute path will result in aRelativePathError.
- is_dir() bool¶
Whether this path exists and is a directory.
Will follow symlinks to determine if the symlink target exists and is a directory.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_fifo() bool¶
Whether this path exists and is a named pipe (also called a FIFO).
Will follow symlinks to determine if the symlink target exists and is a named pipe.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_file() bool¶
Whether this path exists and is a regular file.
Will follow symlinks to determine if the symlink target exists and is a regular file.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_socket() bool¶
Whether this path exists and is a socket.
Will follow symlinks to determine if the symlink target exists and is a socket.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_symlink() bool¶
Whether this path is a symbolic link.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- iterdir() Generator[Self]¶
Yield
ContainerPathobjects corresponding to the directory’s contents.There are no guarantees about the order of the children. The special entries
'.'and'..'are not included.NotADirectoryErroris raised (if appropriate) wheniterdir()is called. This follows the behaviour ofpathlib.Path.iterdirin Python 3.13+. Previous versions deferred the error until the generator was consumed.- Raises:
FileNotFoundError – If this path does not exist.
NotADirectoryError – If this path is not a directory.
PermissionError – If the local or remote user does not have appropriate permissions.
PebbleConnectionError – If the remote container cannot be reached.
- joinpath(*other: str | os.PathLike[str]) Self¶
Return a new ContainerPath with the same container and the new args joined to its path.
- Parameters:
other – Any number of
stroros.PathLikeobjects. If zero are provided, an effective copy of thisContainerPathobject is returned. *other is joined to this object’s path as withos.path.join. This means that if any member of other is an absolute path, all the previous components, including this object’s path, are dropped entirely.- Returns:
A new
ContainerPathwith the sameops.Containerobject, with its path updated with *other as follows. For each item in other, if it is a relative path, it is appended to the current path. If it is an absolute path, it replaces the current path.
Warning
ContainerPathis notos.PathLike. AContainerPathinstance is not a valid value forother, and will result in an error.
- match(path_pattern: str) bool¶
Return whether this path matches the given pattern.
If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard
'**'is not supported by this method. Matching is always case-sensitive. Only the path is matched against, the container is not considered.
- mkdir(
- mode: int = 493,
- parents: bool = False,
- exist_ok: bool = False,
- *,
- user: str | None = None,
- group: str | None = None,
Create a new directory at the corresponding path in the remote container.
Compared to
pathlib.Path.mkdir, this method addsuserandgroupargs. These are used to set the ownership of the created directory. Any created parents will not have their ownership set.- Parameters:
mode – The permissions to set on the created directory. Any parents created will have their permissions set to the default value of 0o755 (drwxr-xr-x). The permissions are not changed if the directory already exists.
parents – Whether to create any missing parent directories as well. If
False(default) and a parent directory does not exist, aFileNotFounderror will be raised.exist_ok – Whether to raise an error if the directory already exists. If
False(default) and the directory already exists, aFileExistsErrorwill be raised.user – The name of the user to set for the directory. If
groupisn’t provided, the user’s default group is used. The user and group are not changed if the directory already exists.group – The name of the group to set for the directory. It is an error to provide
groupifuserisn’t provided. The user and group are not changed if the directory already exists.
- Raises:
FileExistsError – if the directory already exists and
exist_okisFalse.FileNotFoundError – if the parent directory does not exist and
parentsisFalse.LookupError – if the user or group is unknown, or a group is provided without a user.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the remote user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- owner() str¶
Return the user name of the file owner.
- Raises:
FileNotFoundError – If the path does not exist.
PebbleConnectionError – If the remote container cannot be reached.
- property parent: Self¶
The logical parent of this path, as a
ContainerPath.
- property parents: tuple[Self, ...]¶
A sequence of this path’s logical parents. Each parent is a
ContainerPath.
- property parts: tuple[str, ...]¶
A sequence of the components in the filesystem path. The components are strings.
- read_bytes() bytes¶
Read a remote file as bytes and return the contents.
- Returns:
The contents of the the path as byes.
- Raises:
FileNotFoundError – if the parent directory does not exist.
IsADirectoryError – if the target is a directory.
PermissionError – if the Pebble user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- read_text(*, newline: str | None = None) str¶
Read a remote file as text and return the contents as a string.
Compared to pathlib.Path.read_text, this method drops the encoding and errors args. The encoding is assumed to be UTF-8, and any errors encountered will be raised.
- Parameters:
newline – if
None(default), all newlines('\r\n', '\r', '\n')are replaced with'\n'. Otherwise the file contents are returned unmodified.- Returns:
The contents of the the path as a string.
- Raises:
FileNotFoundError – if the parent directory does not exist.
IsADirectoryError – if the target is a directory.
PermissionError – if the Pebble user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- rmdir() None¶
Remove this path if it is an empty directory.
- Raises:
FileNotFoundError – if the path does not exist.
NotADirectoryError – if the path exists but is not a directory.
PermissionError – if the Pebble user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- property suffix: str¶
The path name’s last suffix (if it has any) including the leading
'.'.If the path name doesn’t have a suffix, the result is an empty string.
- property suffixes: list[str]¶
A list of the path name’s suffixes.
Each suffix includes the leading
'.'.If the path name doesn’t have any suffixes, the result is an empty list.
- unlink(missing_ok: bool = False) None¶
Remove this path if it is not a directory.
- Raises:
FileNotFoundError – if the path does not exist and
missing_okis false.IsADirectoryError – if the path exists but is a directory.
PermissionError – if the Pebble user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- with_name(name: str) Self¶
Return a new ContainerPath, with the same container, but with the path name replaced.
The name is the last component of the path, including any suffixes.
container = self.unit.get_container('c') path = ContainerPath('/', 'foo', 'bar.txt', container=container) repr(path.with_name('baz.bin')) # ContainerPath('/foo/baz.bin', container=<ops.Container 'c'>)"
- with_segments(*pathsegments: str | os.PathLike[str]) Self¶
Construct a new
ContainerPath(with the same container) from path-like objects.You can think of this like a copy of the current
ContainerPath, with its path replaced bypathlib.Path(*pathsegments).This method is used internally by all
ContainerPathmethods that return newContainerPathinstances, includingparentandparents. Therefore, subclasses can customise the behaviour of all such methods by overriding only this method. The same is true ofpathlib.Pathin Python 3.12+.
- with_suffix(suffix: str) Self¶
Return a new ContainerPath with the same container and the suffix changed.
- Parameters:
suffix – Must start with a
'.', unless it is an empty string, in which case any existing suffix will be removed entirely.- Returns:
A new instance of the same type, updated as follows. If it contains no
'.', or ends with a'.', thesuffixargument is appended to its name. Otherwise, the last'.'and any trailing content is replaced with thesuffixargument.
- write_bytes(
- data: bytes | bytearray | memoryview,
- *,
- mode: int | None = None,
- user: str | None = None,
- group: str | None = None,
Write the provided data to the corresponding path in the remote container.
Compared to
pathlib.Path.write_bytes, this method addsmode,userandgroupargs. These are forwarded to Pebble, which sets these on file creation.- Parameters:
data – The bytes to write. If data is a
bytearrayormemoryview, it will be converted tobytesin memory first.mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless
modeisNone(default).user – The name of the user to set for the file. If
groupisn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unlessuserisNone(default).group – The name of the group to set for the directory. It is an error to provide
groupifuserisn’t provided. If the file already exists, its group will be changed, unlessuserandgroupareNone(default).
Returns: The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown, or a group is provided without a user.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the Pebble user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- write_text( ) int¶
Write the provided string to the corresponding path in the remote container.
Compared to
pathlib.Path.write_text, this method drops theencodinganderrorsargs to simplify the API. The argsmode,userandgroupare added, and are forwarded to Pebble, which sets these on file creation.- Parameters:
data – The string to write. Will be encoded to
bytesin memory as UTF-8, raising any errors. Newlines are not modified on writing.mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless
modeisNone(default).user – The name of the user to set for the file. If
groupisn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unlessuserisNone(default).group – The name of the group to set for the directory. It is an error to provide
groupifuserisn’t provided. If the file already exists, its group will be changed, unlessuserandgroupareNone(default).
Returns: The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown, or a group is provided without a user.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the Pebble user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- class LocalPath(*args, **kwargs)¶
Bases:
PosixPathpathlib.PosixPathsubclass with extended file-creation method arguments.Note
The
write_bytes,write_text, andmkdirmethods are extended with file permission and ownership arguments, for compatibility withPathProtocol.- Parameters:
*parts –
stroros.PathLike.LocalPathtakes no keyword arguments.
LocalPath(pathlib.Path('/foo')) LocalPath('/', 'foo')
- mkdir(
- mode: int = 493,
- parents: bool = False,
- exist_ok: bool = False,
- *,
- user: str | None = None,
- group: str | None = None,
Create a new directory at the corresponding local filesystem path.
Compared to
pathlib.Path.mkdir, this method addsuserandgroupargs. These are used to set the ownership of the created directory. Any created parents will not have their ownership set.- Parameters:
mode – The permissions to set on the created directory. Any parents created will have their permissions set to the default value of 0o755 (drwxr-xr-x). The permissions are not changed if the directory already exists.
parents – Whether to create any missing parent directories as well. If
False(default) and a parent directory does not exist, aFileNotFounderror will be raised.exist_ok – Whether to raise an error if the directory already exists. If
False(default) and the directory already exists, aFileExistsErrorwill be raised.user – The name of the user to set for the directory using
shutil.chown. Validated to be an existing user before writing. The user and group are not changed if the directory already exists.group – The name of the group to set for the directory using
shutil.chown. Validated to be an existing group before writing. The user and group are not changed if the directory already exists.
- Raises:
FileExistsError – if the directory already exists and
exist_okisFalse.FileNotFoundError – if the parent directory does not exist and
parentsisFalse.LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
- write_bytes( ) int¶
Write the provided data to the corresponding local filesystem path.
Compared to
pathlib.Path.write_bytes, this method addsmode,userandgroupargs. These are used to set the permissions and ownership of the file.- Parameters:
data – The bytes to write, typically a
bytesobject, but may also be abytearrayormemoryview.mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, using
pathlib.PosixPath.chmod, unlessmodeisNone(default).user – The name of the user to set for the file using
shutil.chown. Validated to be an existing user before writing. If the file already exists, its user and group will be changed, unlessuserisNone(default).group – The name of the group to set for the file using
shutil.chown. Validated to be an existing group before writing. If the file already exists, its group will be changed, unlessuserandgroupareNone(default).
- Returns:
The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
- write_text(
- data: str,
- encoding: str | None = None,
- errors: str | None = None,
- newline: str | None = None,
- *,
- mode: int | None = None,
- user: str | None = None,
- group: str | None = None,
Write the provided string to the corresponding local filesystem path.
Compared to
pathlib.Path.write_bytes, this method addsmode,userandgroupargs. These are used to set the permissions and ownership of the file.Warning
ContainerPathandPathProtocoldo not support theencoding,errors, andnewlinearguments ofpathlib.Path.write_text. ForContainerPathcompatible code, do not use these arguments. They are provided to allowLocalPathto be used as a drop-in replacement forpathlib.Pathif needed.- Parameters:
data – The string to write. Newlines are not modified on writing.
encoding – The encoding to use when writing the data, defaults to ‘UTF-8’.
errors – ‘strict’ to raise any encoding errors, ‘ignore’ to ignore them. Defaults to ‘strict’.
newline – If
None,'', or'\n', then ‘n’ will be written as is. This is the default behaviour. Ifnewlineis'\r'or'\r\n', then'\n'will be replaced withnewlinein memory before writing.mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, using
pathlib.PosixPath.chmod, unlessmodeisNone(default).user – The name of the user to set for the file using
shutil.chown. Validated to be an existing user before writing. If the file already exists, its user and group will be changed, unlessuserisNone(default).group – The name of the group to set for the file using
shutil.chown. Validated to be an existing group before writing. If the file already exists, its group will be changed, unlessuserandgroupareNone(default).
- Returns:
The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
ValueError – if
newlineis any value other than those documented above.
- class PathProtocol(*args, **kwargs)¶
Bases:
ProtocolThe protocol implemented by
ContainerPathandLocalPath.Use this class in type annotations where either
ContainerPathorLocalPathis acceptable. This will result in both correct type checking and useful autocompletions.While using a union type will also give correct type checking results, it provides less useful autocompletions, as most editors will autocomplete methods and attributes that any of the union members have, rather than only those that all of the union members have.
strfollows thepathlibconvention and returns the string representation of the path.ContainerPathreturn the string representation of the path in the remote filesystem. The string representation is suitable for use with system calls (on the correct local or remote system) and Pebble layers.Comparison methods compare by path. A
ContainerPathis only comparable to another object if it is also aContainerPathon the sameops.Container. If this is not the case, then equality isFalseand other comparisons areNotImplemented.Protocol implementers are hashable.
Warning
User implementations of
PathProtocolare not covered by this package’s semantic versioning promise.The semantic versioning of this package reflects the runtime use of
ContainerPathandLocalPath.PathProtocolis always updated to reflect the latest changes toContainerPathandLocalPath.PathProtocolwill always be a valid type annotation forContainerPath,LocalPath, andpathlib.PosixPathobjects. However, user implementations ofPathProtocolmay experience type checking breakage on minor version bumps of this package.- __truediv__(key: str | os.PathLike[str]) Self¶
Return a new instance of the same type, with the other operand appended to its path.
Used as
protocol_implementor / str_or_pathlike.Note
__rtruediv__is currently not part of this protocol, asContainerPathobjects only support absolute paths.
- as_posix() str¶
Return the string representation of the path.
Exactly like
pathlib.Pathfor local paths. Following this convention, remote filesystem paths such asContainerPathreturn the string representation of the path in the remote filesystem. The string representation is suitable for use with system calls (on the correct local or remote system) and Pebble layers.Identical to
str, since we only support posix systems.
- exists() bool¶
Whether this path exists.
Will follow symlinks to determine if the symlink target exists. This means that this method will return
Falsefor a broken symlink.- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- glob(pattern: str) Generator[Self]¶
Iterate over this directory and yield all paths matching the provided pattern.
For example,
path.glob('*.txt'),path.glob('*/foo.txt').Warning
Recursive matching, using the
'**'pattern, is not supported byContainerPath.glob.- Parameters:
pattern – Must be relative, meaning it cannot begin with
'/'. Matching is case-sensitive.- Returns:
A generator yielding objects of the same type as this path, corresponding to those of its children which match the pattern. If this path is not a directory, there will be no matches.
- Raises:
FileNotFoundError – If this path does not exist.
NotImplementedError – If pattern is an absolute path, or (in the case of
ContainerPath) if it uses the'**'pattern.PermissionError – If the local or remote user does not have appropriate permissions.
ValueError – If the pattern is invalid.
PebbleConnectionError – If the remote container cannot be reached.
- group() str¶
Return the group name of the file.
- Raises:
FileNotFoundError – If the path does not exist.
PebbleConnectionError – If the remote container cannot be reached.
- is_absolute() bool¶
Return whether the path is absolute (has a root).
Note
Currently always
TrueforContainerPath.
- is_dir() bool¶
Whether this path exists and is a directory.
Will follow symlinks to determine if the symlink target exists and is a directory.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_fifo() bool¶
Whether this path exists and is a named pipe (also called a FIFO).
Will follow symlinks to determine if the symlink target exists and is a named pipe.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_file() bool¶
Whether this path exists and is a regular file.
Will follow symlinks to determine if the symlink target exists and is a regular file.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_socket() bool¶
Whether this path exists and is a socket.
Will follow symlinks to determine if the symlink target exists and is a socket.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- is_symlink() bool¶
Whether this path is a symbolic link.
- Raises:
PebbleConnectionError – If the remote container cannot be reached.
- iterdir() Generator[Self]¶
Yield objects of the same type corresponding to the directory’s contents.
There are no guarantees about the order of the children. The special entries
'.'and'..'are not included.- Raises:
FileNotFoundError – If this path does not exist.
NotADirectoryError – If this path is not a directory.
PermissionError – If the local or remote user does not have appropriate permissions.
PebbleConnectionError – If the remote container cannot be reached.
- joinpath(*other: str | os.PathLike[str]) Self¶
Return a new instance of the same type, with its path joined with the arguments.
- Parameters:
other – Any number of
stroros.PathLikeobjects.- Returns:
A new instance of the same type, updated as follows. For each item in other, if it is a relative path, it is appended to the current path. If it is an absolute path, it replaces the current path.
Warning
ContainerPathis notos.PathLike. AContainerPathinstance is not a valid value forother, and will result in an error.
- match(path_pattern: str) bool¶
Return whether this path matches the given pattern.
If the pattern is relative, matching is done from the right; otherwise, the entire path is matched. The recursive wildcard
'**'is not supported by this method. Matching is always case-sensitive.
- mkdir(
- mode: int = 493,
- parents: bool = False,
- exist_ok: bool = False,
- *,
- user: str | None = None,
- group: str | None = None,
Create a new directory at the corresponding path.
Compared to
pathlib.Path.mkdir, this method addsuserandgroupargs. These are used to set the ownership of the created directory. Any created parents will not have their ownership set.- Parameters:
mode – The permissions to set on the created directory. Any parents created will have their permissions set to the default value of 0o755 (drwxr-xr-x). The permissions are not changed if the directory already exists.
parents – Whether to create any missing parent directories as well. If
False(default) and a parent directory does not exist, aFileNotFounderror will be raised.exist_ok – Whether to raise an error if the directory already exists. If
False(default) and the directory already exists, aFileExistsErrorwill be raised.user – The name of the user to set for the directory. If
groupisn’t provided, the user’s default group is used. The user and group are not changed if the directory already exists.group – The name of the group to set for the directory. For
ContainerPath, it is an error to providegroupifuserisn’t provided. The user and group are not changed if the directory already exists.
- Raises:
FileExistsError – if the directory already exists and
exist_okisFalse.FileNotFoundError – if the parent directory does not exist and
parentsisFalse.LookupError – if the user or group is unknown, or a group is provided without a user.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the local user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- owner() str¶
Return the user name of the file owner.
- Raises:
FileNotFoundError – If the path does not exist.
PebbleConnectionError – If the remote container cannot be reached.
- property parent: Self¶
The logical parent of this path. An instance of this type.
- property parents: Sequence[Self]¶
A sequence of this path’s logical parents. Each parent is an instance of this type.
- read_bytes() bytes¶
Read the corresponding local or remote filesystem path and return the binary contents.
- Returns:
The file’s raw contents as
bytes.- Raises:
FileNotFoundError – If this path does not exist.
PermissionError – If the local or remote user does not have read permissions.
PebbleConnectionError – If the remote container cannot be reached.
- read_text() str¶
Read the corresponding local or remote filesystem path and return the string contents.
Compared to
pathlib.Path.read_text, this method drops theencodinganderrorsargs to simplify the API.- Returns:
The UTF-8 decoded contents of the file as a
str.- Raises:
FileNotFoundError – If this path does not exist.
PermissionError – If the local or remote user does not have read permissions.
UnicodeError – If the file’s contents are not valid UTF-8.
PebbleConnectionError – If the remote container cannot be reached.
- rmdir() None¶
Remove this path if it is an empty directory.
- Raises:
FileNotFoundError – if the path does not exist.
NotADirectoryError – if the path exists but is not a directory.
PermissionError – if the local or remote user does not have the appropriate permissions.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- property suffix: str¶
The path name’s last suffix (if it has any) including the leading
'.'.If the path name doesn’t have a suffix, the result is an empty string.
- property suffixes: list[str]¶
A list of the path name’s suffixes.
Each suffix includes the leading
'.'.If the path name doesn’t have any suffixes, the result is an empty list.
- unlink(missing_ok: bool = False) None¶
Remove this path if it is not a directory.
- Raises:
FileNotFoundError – if the path does not exist and
missing_okis false.IsADirectoryError – if the path exists but is a directory.
PermissionError – if the local or remote user does not have the appropriate permissions.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- with_name(name: str) Self¶
Return a new instance of the same type, with the path name replaced.
The name is the last component of the path, including any suffixes.
- with_suffix(suffix: str) Self¶
Return a new instance of the same type, with the path suffix replaced.
- Parameters:
suffix – Must start with a
'.', unless it is an empty string, in which case any existing suffix will be removed entirely.- Returns:
A new instance of the same type, updated as follows. If it contains no
'.', or ends with a'.', thesuffixargument is appended to its name. Otherwise, the last'.'and any trailing content is replaced with thesuffixargument.
- write_bytes( ) int¶
Write the provided data to the corresponding path.
Compared to
pathlib.Path.write_bytes, this method addsmode,userandgroupargs, which are set on file creation.- Parameters:
data – The bytes to write, typically a
bytesobject, but may also be abytearrayormemoryview.mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless
modeisNone(default).user – The name of the user to set for the directory. If
groupisn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unlessuserisNone(default).group – The name of the group to set for the directory. For
ContainerPath, it is an error to providegroupifuserisn’t provided. If the file already exists, its group will be changed, unlessuserandgroupareNone(default).
- Returns:
The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown, or a group is provided without a user.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- write_text( ) int¶
Write the provided string to the corresponding path.
Compared to
pathlib.Path.write_text, this method drops theencodinganderrorsargs to simplify the API. This method addsmode,userandgroupargs, which are set on file creation.- Parameters:
data – The string to write. Newlines are not modified on writing.
mode – The permissions to set on the file. Defaults to 0o644 (-rw-r–r–) for new files. If the file already exists, its permissions will be changed, unless
modeisNone(default).user – The name of the user to set for the directory. If
groupisn’t provided, the user’s default group is used. If the file already exists, its user and group will be changed, unlessuserisNone(default).group – The name of the group to set for the directory. For
ContainerPath, it is an error to providegroupifuserisn’t provided. If the file already exists, its group will be changed, unlessuserandgroupareNone(default).
- Returns:
The number of bytes written.
- Raises:
FileNotFoundError – if the parent directory does not exist.
LookupError – if the user or group is unknown, or a group is provided without a user.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the user does not have permissions for the operation.
UnicodeError – if the provided data is not valid UTF-8.
PebbleConnectionError – if the remote Pebble client cannot be reached.
- PebbleConnectionError¶
alias of
ConnectionError
- exception RelativePathError¶
Bases:
ValueErrorContainerPath only supports absolute paths.
This is because Pebble only works with absolute paths. Relative path support will likely remain unavailable at least until Pebble supports relative paths. In the meantime, use absolute paths.
- ensure_contents(
- path: str | os.PathLike[str] | PathProtocol,
- source: bytes | str | BinaryIO | TextIO,
- *,
- mode: int = 420,
- user: str | None = None,
- group: str | None = None,
Ensure
sourcecan be read frompath. Return True if any changes were made.Ensure that
pathexists, containssource, has the correct permissions (mode), and has the correct file ownership (userandgroup).- Parameters:
path – A local or remote filesystem path.
source – The desired contents in
strorbytesform, or an object with a.read()method which returns astrorbytesobject.mode – The desired file permissions.
user – The desired file owner, or
Noneto not change the owner.group – The desired group, or
Noneto not change the group.
- Returns:
Trueif any changes were made, including permissions or ownership, otherwiseFalse.- Raises:
LookupError – if the user or group is unknown.
NotADirectoryError – if the parent exists as a non-directory file.
PermissionError – if the user does not have permissions for the operation.
PebbleConnectionError – if the remote Pebble client cannot be reached.