我对 Python 很陌生,我很难理解使用 Python 的某些方面。
我正在编写代码来使用pyvisa控制几个仪器。为简单起见,我在这里只展示一种仪器(Thor Labs 功率计)。如果我将所有代码放在一个文件中,我可以让事情正常工作。下面的代码首先搜索可用的仪器,并定义仪器 ID ( ThorID ):
import pyvisa
rm = pyvisa.ResourceManager() # Set up resource manager
resource_list = rm.list_resources() # Create a list of available instruments
# Thor Labs power meters should contain this string
Thor_str = "0x1313::0x8079"
# Search for a Thor Labs meter in the resource list
Thor = [i for i, s in enumerate(resource_list) if Thor_str in s]
if len(Thor) == 0:
print("No Thor Labs power meter detected")
ThorID = ""
else:
print("Thor Labs power meter detected")
ThorID = resource_list[Thor[0]] # This is the Thor Labs VISA ID
然后我定义类功率计
class powermeter:
"Power meter class. Contains parameter values and commands."
def __init__(self, wavelength=450, meter_range=200e-3, id=ThorID):
""" Define default parameter values """
self.wavelength = wavelength # nm
self.meter_range = meter_range # W
self.ID = id # Meter's VISA ID
self.name = "" # Meter instance name
def connect(self):
"""Open a connection to the power meter"""
self.name = rm.open_resource(self.ID)
def set_wavelength(self, wavelength):
"""Set the power meter wavelength (nm)"""
self.name.write("CORR:WAV " + str(wavelength))
def set_range(self, meter_range):
"""Set the power meter range (W)"""
self.name.write("POW:DC:RANG " + str(meter_range))
def read(self):
"""Read the power meter output (mW)"""
return float(self.name.query("READ?"))*1000
最后 3 行打开与仪表的连接并设置波长(至 400 nm)。我可以在一个 .py 文件中确认所有这些代码是否有效。
enter pm = powermeter() # Create instance of powermeter
pm.connect() # Connect to this power meter
pm.set_wavelength(400) # Set wavelength to 400 nm
尝试将 Class 拆分为单独的 .py 文件时遇到了很多麻烦。我想这样做是为了让我的代码更整洁......最终我将添加一个 GUI 和另一个类,我不想要一个巨大的繁琐的文本单体。
我天真的第一次尝试将此作为我的主要代码,上面编写的类保存在PM_class.py中:
import pyvisa
rm = pyvisa.ResourceManager() # Set up resource manager
resource_list = rm.list_resources() # Create a list of available instruments
# Thor Labs power meters should contain this string
Thor_str = "0x1313::0x8079"
# Search for a Thor Labs meter in the resource list
Thor = [i for i, s in enumerate(resource_list) if Thor_str in s]
if len(Thor) == 0:
print("No Thor Labs power meter detected")
ThorID = ""
else:
print("Thor Labs power meter detected")
ThorID = resource_list[Thor[0]] # This is the Thor Labs VISA ID
from PM_class.py import powermeter
但我在PM_class.py中收到错误- NameError: name 'ThorID' is not defined
我不明白,因为在我尝试导入类之前,ThorID 已在该行中明确定义?
任何有关如何解决此问题的建议都将非常受欢迎!