Tutorial

OPC UA with Python: asyncua tutorial

The quickest way to get OPC UA is to talk to a server in code. This tutorial uses asyncua (the free, open-source opcua-asyncio library) to connect, browse, read, write and subscribe: the four things you'll do 90% of the time.

To use OPC UA in Python, install the open-source asyncua library (pip install asyncua), connect a Client to the server's opc.tcp:// endpoint, then browse, read, write or subscribe to nodes by NodeId. asyncua covers both client and server, is built on asyncio and ships a synchronous wrapper (asyncua.sync) for scripts; the older python-opcua package is deprecated.

Which Python OPC UA library should you use?

LibraryRoleStatusLicenceUse it when
asyncua (opcua-asyncio)Client and serverMaintained; 2.1.0 released 6 Oct 2026; needs Python 3.10+LGPL-3.0-or-laterDefault choice for new code
asyncua.syncSynchronous wrapperShips with asyncuaSame as asyncuaScripts and notebooks without async code
python-opcua (import opcua)Client and serverDeprecated by its maintainersLGPL-3.0Only to maintain existing code

Versions and licences from PyPI and the projects' repositories, checked 2 December 2026. Other languages: OPC UA SDKs compared.

Prerequisites: Python 3.10 or later (required by current asyncua releases), and any OPC UA server to point at (a simulator, the open62541 demo server, or your PLC). No server yet? See free tools & test servers.

1. Install

pip install asyncua

2. Connect and read a value

import asyncio
from asyncua import Client

URL = "opc.tcp://localhost:4840/freeopcua/server/"

async def main():
    async with Client(url=URL) as client:
        # Read a node by its NodeId (namespace index + identifier)
        node = client.get_node("ns=2;i=2")
        value = await node.read_value()
        print("Value:", value)

asyncio.run(main())

3. Browse the address space

async with Client(url=URL) as client:
    objects = client.nodes.objects
    for child in await objects.get_children():
        name = await child.read_browse_name()
        print(name)

4. Write a value

from asyncua import ua

async with Client(url=URL) as client:
    node = client.get_node("ns=2;i=3")
    await node.write_value(ua.DataValue(ua.Variant(42.0, ua.VariantType.Double)))
Writes are often blocked by server permissions. If it fails, confirm the node is writable and your user is authorised: see troubleshooting.

5. Subscribe to data changes

Subscriptions push updates to you instead of polling: the right way to watch a value.

class Handler:
    def datachange_notification(self, node, val, data):
        print("Change:", node, val)

async with Client(url=URL) as client:
    handler = Handler()
    sub = await client.create_subscription(500, handler)  # 500 ms
    node = client.get_node("ns=2;i=2")
    await sub.subscribe_data_change(node)
    await asyncio.sleep(30)   # keep running to receive changes

Prefer synchronous code?

For a quick script or a notebook, the synchronous wrapper avoids asyncio entirely:

from asyncua.sync import Client

with Client("opc.tcp://localhost:4840/freeopcua/server/") as client:
    node = client.get_node("ns=2;i=2")
    print(node.read_value())

How do you build an OPC UA server in Python?

asyncua also runs a server: useful as a simulator for testing clients, dashboards and historians before the real machine is available.

import asyncio
from asyncua import Server

async def main():
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
    idx = await server.register_namespace("urn:example:line1")
    line = await server.nodes.objects.add_object(idx, "Line1")
    speed = await line.add_variable(idx, "Speed", 0.0)
    await speed.set_writable()          # let clients write it
    async with server:
        while True:
            await asyncio.sleep(1)
            await speed.write_value(await speed.read_value() + 1.0)

asyncio.run(main())

Clients find your variables by namespace URI rather than index: idx = await client.get_namespace_index("urn:example:line1"). To load a whole information model instead of building nodes in code, import a NodeSet2 file with await server.import_xml(...).

Connecting securely

For Sign & Encrypt, load your certificate and key before connecting:

await client.set_security_string(
    "Basic256Sha256,SignAndEncrypt,client-cert.der,client-key.pem")

The server must trust your certificate (move it from rejected to trusted). Details: OPC UA security & certificates.

Common Python OPC UA errors and fixes

ErrorUsual causeFix
BadCertificateUntrustedThe server does not trust your client certificate yetMove the certificate from the server's rejected folder to trusted, then reconnect
BadSecurityChecksFailedCertificate or security settings rejectedCheck the certificate's ApplicationUri, validity dates and the security policy the endpoint offers
BadUserAccessDeniedAnonymous or wrong userSet credentials with client.set_user() and client.set_password() before connecting
BadNodeIdUnknownNodeId or namespace index is wrong on this serverResolve the index with get_namespace_index(); browse to confirm the identifier
BadNotWritable / BadTypeMismatchRead-only node, or a value of the wrong DataTypeConfirm write access; write a ua.Variant of the node's DataType
TimeoutError / BadTimeoutEndpoint unreachable: wrong host or port, firewall on 4840Test the endpoint with UaExpert first, then follow the troubleshooting guide

Going further: OPC UA data into pandas and Jupyter · the same client and server in four languages.

Collecting machine data in Python to track performance? TEEPTRAK measures OEE, stops and micro-stops in real time, with AI agents that answer plain-language questions from the plant's own measured data. JEMBA, a separate TEEPTRAK Group product, adds machine-learning anomaly detection and setpoint optimisation.

OPC UA into TEEPTRAK →

FAQ

Which Python OPC UA library should I use?
asyncua (opcua-asyncio) is the actively maintained library and the usual choice: client and server, asyncio-based, LGPL-3.0-or-later. The older synchronous python-opcua package is deprecated by its maintainers in favour of asyncua.
Is there a synchronous (non-async) Python OPC UA API?
Yes. asyncua ships asyncua.sync, a synchronous wrapper with almost the same API, for scripts and notebooks where you do not want to write async code.
Can I build an OPC UA server in Python?
Yes: asyncua includes a server implementation, handy for simulators, test fixtures and small gateways. For embedded or constrained targets a C stack such as open62541 is the usual choice.
Which Python version does asyncua need?
Current asyncua releases require Python 3.10 or later (asyncua 2.1.0, released 6 October 2026, according to PyPI).
Why does my read fail with BadNodeIdUnknown?
The NodeId does not exist on that server, most often because the namespace index differs from the one in your code. Look the index up from the namespace URI with get_namespace_index() instead of hard-coding ns=2.
What is a NodeId?
The unique address of a node, e.g. ns=2;i=2 (namespace index 2, integer identifier 2) or ns=3;s=Temperature (string identifier).

Last updated 2 December 2026 (library table, server example, sync API and error fixes added; versions checked on PyPI) · Educational resource. Library names are trademarks of their owners.

Next: OPC UA & PLCs (Siemens TIA Portal) →

Free download
OPC UA Troubleshooting & Integration Checklist
The field-tested checklist engineers use to diagnose certificates, ports and namespace problems fast, plus a Python (asyncua) client template.
Get the free checklist →
Free, no course, no login