Tutorial
OPC UA with Python
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.
Prerequisites: Python 3.8+, 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
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.
Reading nodes in Python is step one. Turning that stream into ranked, costed actions on the floor is what Jemba does.
See Jemba →FAQ
Which Python OPC UA library should I use?
asyncua (opcua-asyncio) is the actively maintained, async library and the usual choice. The older synchronous python-opcua is deprecated in its favour.Can I build an OPC UA server in Python?
Yes: asyncua includes a full server implementation, handy for simulators and tests.
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 4 September 2026 · Educational resource. Library names are trademarks of their owners.