Inside the Python support in QuickOPC

From OPC Labs Knowledge Base
Jump to navigation Jump to search

QuickOPC can currently be used from Python using two approaches: With the help of Python.NET (the new, recommended approach), and over Microsoft COM (older approach, deprecated).

QuickOPC with Python.NET

In this approach, the Python.NET package (pythonnet) is used to expose .NET API of QuickOPC to Python. This is the recommended way of using QuickOPC from Python, and we continue developing it further. QuickOPC contains extensive set of examples for most its functionality areas, and using Python.NET.

OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .

.NET Runtime Initialization

The Python.NET package requires that the .NET runtime is loaded (initialized) before the .NET types can be used from Python. The Python.NET contains instructions on how to do that from your code.

In an effort to make the programming as seamless as possible, QuickOPC does this initialization step for you, automatically. When multiple runtimes are available on the machine, QuickOPC automatically chooses one. The both .NET Framework 4.7.2+ and .NET 6+, the preference is given to .NET 4.7.2+. If you want to change this, set the environment variable PYTHONNET_RUNTIME to 'coreclr' before importing any of the QuickOPC modules. It can be done e.g. by placing "import os" and "os.environ['PYTHONNET_RUNTIME']='coreclr'" statements before the "import opclabs_quickopc" statement.

Note that QuickOPC Windows Forms features do not currently work in Python with the .NET 6+ runtime.

QuickOPC with Python (COM)

In this approach, the pypiwin32 Python package is used to access QoickOPC COM API from Python. For the reasons explained further below, this approach is now deprecated. The examples using the COM approach remain in the product, at least for the time being.

The disadvantages of the COM approach include:

  • Strictly limited to Windows only.
  • Multiple layers involved (QuickOPC is .NET API primarily, the COM API layer sits on top of it, then Python layer accesses this COM API), with performance and possibly also reliability implications.
  • The fact that COM API is involved "in the middle" precludes usage of many .NET features, such as generics, methods overloads, or callbacks.
  • Cumbersome coding.
  • The pypiwin32 package is poorly documented, and does not appear to be very actively maintained.
  • Apparent impossibility to make the event notifications work.