Quickstart

"Hello world", sync API:

from pyroute2 import IPRoute

def main():
    ipr = IPRoute()
    for link in ipr.link("dump"):
        print(link.get("ifname"), link.get("state"), link.get("address"))
    ipr.close()

main()
lo up 00:00:00:00:00:00
eth0 up 52:54:00:72:58:b2

"Hello world", async API:

import asyncio

from pyroute2 import AsyncIPRoute


async def main():
    ipr = AsyncIPRoute()
    async for link in await ipr.link("dump"):
        print(link.get("ifname"), link.get("state"), link.get("address"))
    await ipr.close()

asyncio.run(main())
lo up 00:00:00:00:00:00
eth0 up 52:54:00:72:58:b2

Resource release

Do not forget to release resources and close sockets. Also keep in mind, that the real fd will be closed only when the Python GC will collect closed objects.

Imports

The public API is exported by pyroute2/__init__.py.

It is done so to provide a stable API that will not be affected by changes in the package layout. There may be significant layout changes between versions, but if a symbol is re-exported via pyroute2/__init__.py, it will be available with the same import signature.

Warning

All other objects are also available for import, but they may change signatures in the next versions.

E.g.:

# Import a pyroute2 class directly. In the next versions
# the import signature can be changed, e.g., NetNS from
# pyroute2.netns.nslink it can be moved somewhere else.
#
from pyroute2.iproute.linux import NetNS
ns = NetNS('test')

# Import the same class from root module. This signature
# will stay the same, any layout change is reflected in
# the root module.
#
from pyroute2 import NetNS
ns = NetNS('test')