libnbd-python3
How to use libnbd from python
Usage
#!/usr/bin/python3import nbdh = nbd.NBD()h.connect_uri("nbd://localhost")sector = h.pread(512, 0)
Overview
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.
Handles
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
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 beconnected 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"
Buffers
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.