Skip to content

Instantly share code, notes, and snippets.

@wcheek
Last active April 13, 2022 03:55
Show Gist options
  • Save wcheek/35599f2db14592129c358f3b35988d16 to your computer and use it in GitHub Desktop.
Save wcheek/35599f2db14592129c358f3b35988d16 to your computer and use it in GitHub Desktop.
pymodbus context manager - manage TCP connection

A simple context manager to manage the connection to a TCP Modbus slave using pymodbus.

from pymodbus.client.sync import ModbusTcpClient
class ModbusConnection:
def __init__(self, host, port):
self.host = host
self.port = port
def __enter__(self):
self.client = ModbusTcpClient(host=self.host, port=self.port)
self.client.connect
return self.client
def __exit__(self, exc_type, exc_val, exc_tb):
if self.client:
self.client.close()
with ModbusConnection(host=..., port=...) as client:
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment