使用 Python 節點將 Python 資料結構傳入/傳出 LabVIEW

更新 Jan 2, 2025

環境

軟體

  • LabVIEW

程式語言

  • Python

本文說明如何設定 Tuples (元組)/ Cluster (簇)、陣列/清單等複雜資料結構,以使用 LabVIEW Python 節點在 LabVIEW 和 Python 環境之間進行傳輸,以達到 LabVIEW 和 Python 相互溝通的目的,讓您能更好地利用兩種語言的優勢達到最佳功能。

本文會使用LabVIEW讀取Python資料,將這些資料從 LabVIEW 寫入 Python 也是相同的道理,只是方向不同。

請注意,標準資料類型(例如無符號或有符號數位、字串、布林值)會由 Python 節點自動轉換。

如果使用 LabVIEW 陣列和 Python List (列表):

當提供正確的資料類型作為輸入時,Python節點將自動將受支援的Python資料類型的任何LabVIEW陣列轉換為該資料類型的Python List。

Python程式碼如下:

TestList = [True, True, False]
def return_list():
    x = TestList
    return x

它會在 LabVIEW 中傳回布林陣列: 
LabVIEW_OEYlyBO8LN.png

如果使用 LabVIEW Cluster 和 Python Tuples (元組):

Python 節點將轉換支援資料類型的 Cluster 或 Tuple元組。
下面的Python程式碼結合上面的TestList定義:

TestTuple = (3, 5, "TestList")
def return_tuple():
    x = [TestTuple, TestTuple]
    return x


當給定正確的資料類型時,將傳回以下 LabVIEW Cluster: LabVIEW_NjfD5Kodg7.png
這也適用於命名元組。

如果使用帶有命名對的Python字典和LabVIEW群集:

LabVIEW中沒有 Python 字典對應的型別,它儲存在 Key:Value 對中。
相反地,請使用 JSON 字串進行此通訊。以下為Python程式碼:

import json
TestDict = {
    "String": "Test",
    "Number": 2,
    "Other number": 3
}

def return_dict():
    x = json.dumps(TestDict)  
    return x

透過LabVIEW可以讀取如下:
LabVIEW_MYlij8HFjF.png

LabVIEW Cluster 內變數的命名非常重要。

完整程式碼

上述 LabVIEW 程式碼的完整片段如下:
Python 呼叫片段.png

同樣,本文的完整 Python 腳本可以在下面找到:

import json ##Required for the dict conversion

TestList = [True, True, False]
def return_list():
    x = TestList
    return x
##
TestTuple = (3, 5, "TestList")
def return_tuple():
    x = [TestTuple, TestTuple]
    return x
##
TestDict = {
    "String": "Test",
    "Number": 2,
    "Other number": 3
}

def return_dict():
    x = json.dumps(TestDict) 
    return x