TLDR:我正在为 LabVIEW 使用的东西制作一个 python 包装器,我想传递一个 dict
(甚至是 kwargs)[即键/值对] 到 python 脚本,这样我就可以有更多的动态函数参数。
LabVIEW 2018 实现了一个 Python Node它允许 LabVIEW 通过调用、传递和获取返回的变量与 python 脚本进行交互。
问题是它似乎没有对 dict
类型的原生支持:
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.
当然 python 是围绕字典构建的,但 LabVIEW 似乎不支持任何传递字典对象的方式。
有谁知道我可以将一组命名元素(或任何其他字典类型)作为 dict
对象传递给 python 脚本的方法吗?
最佳答案
没有直接的方法。
双方最简单的方法是使用 JSON 字符串。
从LabVIEW到Python
LabVIEW 集群可以扁平化为 JSON(字符串 > 扁平化/非扁平化):
生成的字符串可以在一行中转换为 dict(加上 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
从 Python 到 LabVIEW
Python 方面又简单了:
>>> MyJson = json.dumps(myDict)
在 LabVIEW 中,从字符串中展开 JSON,并使用默认值连接预期结构的簇:
这当然需要dict的结构是固定的。 如果不是,您仍然可以通过将它们的路径作为数组来访问单个元素:
限制:
虽然这很有效(您是否注意到我的语言环境使用逗号作为小数点符号?),但并非所有数据类型都受支持。例如,JSON 本身没有时间数据类型,也没有专门的路径数据类型,因此 JSON VI 拒绝处理它们。使用数字或字符串数据类型,并在 LabVIEW 中进行转换。
Excourse:LabVIEW 中的字典式数据类型
如果您在 LabVIEW 中需要动态数据类型,请查看变量的属性。 这些是成对的键(字符串)和值(任何数据类型!),可以像在 Python 中一样简单地添加和读取它们。但是没有(内置的,简单的)方法可以使用它与 Python 交换数据。
关于python - 通过 Python 节点将字典从 LabVIEW 传递到 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56282070/