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?
| Library | Role | Status | Licence | Use it when |
|---|---|---|---|---|
asyncua (opcua-asyncio) | Client and server | Maintained; 2.1.0 released 6 Oct 2026; needs Python 3.10+ | LGPL-3.0-or-later | Default choice for new code |
asyncua.sync | Synchronous wrapper | Ships with asyncua | Same as asyncua | Scripts and notebooks without async code |
python-opcua (import opcua) | Client and server | Deprecated by its maintainers | LGPL-3.0 | Only to maintain existing code |
Versions and licences from PyPI and the projects' repositories, checked 2 December 2026. Other languages: OPC UA SDKs compared.
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)))
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
| Error | Usual cause | Fix |
|---|---|---|
BadCertificateUntrusted | The server does not trust your client certificate yet | Move the certificate from the server's rejected folder to trusted, then reconnect |
BadSecurityChecksFailed | Certificate or security settings rejected | Check the certificate's ApplicationUri, validity dates and the security policy the endpoint offers |
BadUserAccessDenied | Anonymous or wrong user | Set credentials with client.set_user() and client.set_password() before connecting |
BadNodeIdUnknown | NodeId or namespace index is wrong on this server | Resolve the index with get_namespace_index(); browse to confirm the identifier |
BadNotWritable / BadTypeMismatch | Read-only node, or a value of the wrong DataType | Confirm write access; write a ua.Variant of the node's DataType |
TimeoutError / BadTimeout | Endpoint unreachable: wrong host or port, firewall on 4840 | Test 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?
Is there a synchronous (non-async) Python OPC UA API?
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?
Which Python version does asyncua need?
Why does my read fail with BadNodeIdUnknown?
get_namespace_index() instead of hard-coding ns=2.What is a NodeId?
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.