4

TLDR: I am making a python wrapper around something for LabVIEW to use and I want to pass a dict (or even kwargs) [i.e. key/value pairs] to a python script so I can have more dynamic function arguments.

LabVIEW 2018 implemented a Python Node which allows LabVIEW to interact with python scripts by calling, passing, and getting returned variables.

The issue is it doesn't appear to have native support for the dict type:

Python Node Details Supported Data Types

The Python Node supports a large number of data types. You can use this node to call the following data types:

Numerics Arrays, including multi-dimensional arrays Strings Clusters Calling Conventions

This node converts integers and strings to the corresponding data types in Python, converts arrays to lists, and converts clusters to tuples.

Of course python is built around dictionaries but it appears LabVIEW does not support any way to pass a dictionary object.

Does anyone know of a way I can pass a cluster of named elements (or any other dictionary type) to a python script as a dict object?

1 Answers1

5

There is no direct way to do it.

The simplest way on both sides would be to use JSON strings.

From LabVIEW to Python

LabVIEW Clusters can be flattened to JSON (Strings > Flatten/unflatten):

enter image description here

The resulting string can be converted to a dict in just one line (plus an import) python:

>>> import json
>>> myDict=json.loads('{"MyString":"FooBar","MySubCluster":{"MyInt":42,"MyFloat":3.1410000000000000142},"myIntArray":[1,2,3]}')
>>> myDict
{u'MyString': u'FooBar', u'MySubCluster': {u'MyInt': 42, u'MyFloat': 3.141}, u'myIntArray': [1, 2, 3]}
>>> myDict['MySubCluster']['MyFloat']
3.141

From Python to LabVIEW

The Python side is easy again:

>>> MyJson = json.dumps(myDict)

In LabVIEW, unflatten JSON from string, and wire a cluster of the expected structure with default values:

enter image description here

This of course requires that the structure of the dict is fixed. If it is not, you can still access single elements by giving the path to them as array:

enter image description here

Limitations:

While this works like a charm (did you even notice that my locale uses comma as decimal sign?), not all datatypes are supported. For example, JSON itself does not have a time datatype, nor a dedicated path datatype, and so, the JSON VIs refuse to handle them. Use a numerical or string datatype, and convert it within LabVIEW.

Excourse: A dict-ish datatype in LabVIEW

If you ever need a dynamic datatype in LabVIEW, have a look at attributes of variants. These are pairs of keys (string) and values (any datatype!), which can be added and reads about as simple as in Python. But there is no (builtin, simple) way to use this to interchange data with Python.

enter image description here

sweber
  • 2,916
  • 2
  • 15
  • 22