如何通过Python COM/ActiveX访问LabVIEW项目内运行的VI实例
问题根本原因
LabVIEW会为项目内加载的VI创建独立的内存实例,和直接从文件系统双击打开的同路径VI属于两个完全独立的对象。默认调用getvireference传入本地文件路径时,只会匹配独立打开的VI实例,不会关联项目内加载的运行中实例。
解决方案1:通过项目引用定位目标VI
优先获取已打开的LabVIEW项目引用,再从项目的项集合中定位目标VI,不要直接用本地文件路径调用getvireference,示例代码如下:
from icecream import ic import win32com.client import time import numpy as np class LabView(): def __init__(self, project_path, vi_project_path): self.LabVIEW = win32com.client.Dispatch("Labview.Application") # 先获取项目引用,project_path是.lvproj项目文件的本地路径 self.project = self.LabVIEW.GetProjectReference(project_path) # 从项目中获取VI引用,vi_project_path是VI在项目内的层级路径,比如"My Computer/test.vi" self.VI = self.project.GetVIReference(vi_project_path) def set_potential(self,potential): ic(potential) self.VI.SetControlValue("Set Potential",potential) # 替换为你的实际项目路径和VI在项目内的路径 project_path = r'C:\path...\testProject\testProject.lvproj' vi_in_project_path = r'My Computer\test.vi' lab = LabView(project_path, vi_in_project_path) while True: lab.set_potential(np.random.uniform(-2,2)) time.sleep(3)
解决方案2:枚举所有运行中VI匹配目标
如果不想硬编码项目路径,也可以枚举当前LabVIEW进程中所有已加载的VI,筛选出运行状态、路径匹配的目标实例:
class LabView(): def __init__(self, vi_file_path): self.LabVIEW = win32com.client.Dispatch("Labview.Application") # 枚举所有已加载的VI all_vis = self.LabVIEW.GetVIReferences() target_vi = None for vi in all_vis: # 匹配VI的本地文件路径和运行状态,ExecState=2代表VI正在运行 if vi.Path == vi_file_path and vi.ExecState == 2: target_vi = vi break if not target_vi: # 没找到运行中的实例,按原逻辑加载 target_vi = self.LabVIEW.getvireference(vi_file_path) self.VI = target_vi def set_potential(self,potential): ic(potential) self.VI.SetControlValue("Set Potential",potential) vi = r'C:\path...\testProject\test.vi' lab = LabView(vi)
注意事项
- 如果同时打开了多个LabVIEW进程,需要用
win32com.client.GetActiveObject绑定指定的进程,避免获取到错误的LabVIEW实例 - 如果项目内有多个重名VI,建议增加VI的所属项目路径判断,避免匹配错误
内容的提问来源于stack exchange,提问作者MayorChemical
相关产品推荐
相关产品推荐

