libnbd-python - how to use libnbd from Python
#!/usr/bin/python3
import nbd
h = nbd.NBD()
h.connect_uri("nbd://localhost")
sector = h.pread(512, 0)
This manual page documents how to use libnbd to access Network Block Device (NBD) servers from the Python programming language. The Python bindings work very similarly to the C bindings so you should start by reading libnbd(3).
There is a convenient interactive command line shell called nbdsh(1) which makes it easier to play with the Python API.
Detailed documentation of the Python API is provided in the Python code. To read it, open nbdsh(1) and type:
help(nbd)
There are some example Python scripts in the libnbd source repository under python/examples or see https://gitlab.com/nbdkit/libnbd/tree/master/python/examples.
Create a libnbd handle by calling nbd.NBD()
.
You can either close the handle explicitly with h.close()
(added in libnbd 1.16), or it will be closed automatically when it goes out of scope.
Calling any method on a handle that has been closed will raise nbd.ClosedHandle
.
Errors from API calls are turned into the Python nbd.Error
exception (derived from Exception
). The nbd.Error
object has three properties of interest:
ex.string
The full error message as a printable string.
Example: "nbd_pread: invalid state: START: the handle must be connected with the server: Transport endpoint is not connected"
ex.errnum
The errno object (from the Python errno
module), if this is available. Not all errors that are raised will have an errno.
Example: errno.EINVAL
For common error codes see "Errno" in libnbd(3).
ex.errno
The errno as a string (or None
if this is not available).
Example: "ENOTCONN"
Synchronous calls (eg. h.pwrite
, h.pread
) take and return normal Python bytearray
s.
Asynchronous calls (eg. h.aio_pwrite
, h.aio_pread
) use the nbd.Buffer
type, which is a persistent, modifiable, zero-copy buffer. The buffer also supports indexing and slicing. These are more complicated to use, and in particular the caller must ensure the buffer remains valid while the asynchronous operation is taking place.
Richard W.M. Jones
Copyright Red Hat
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA