我正在使用pyvisa通过 USB 与仪器进行通信。我能够正确控制它。由于它是高压源,并且打开高压时忘记它很危险,我想实现该__del__
方法以在代码执行完成时关闭输出。所以基本上我写了这个:
import pyvisa as visa
class Instrument:
def __init__(self, resource_str='USB0::1510::9328::04481179::0::INSTR'):
self._resource_str = resource_str
self._resource = visa.ResourceManager().open_resource(resource_str)
def set_voltage(self, volts: float):
self._resource.write(f':SOURCE:VOLT:LEV {volts}')
def __del__(self):
self.set_voltage(0)
instrument = Instrument()
instrument.set_voltage(555)
问题是它不工作并且在我得到的终端中
$ python3 comunication\ test.py
Exception ignored in: <function Instrument.__del__ at 0x7f4cca419820>
Traceback (most recent call last):
File "comunication test.py", line 12, in __del__
File "comunication test.py", line 9, in set_voltage
File "/home/superman/.local/lib/python3.8/site-packages/pyvisa/resources/messagebased.py", line 197, in write
File "/home/superman/.local/lib/python3.8/site-packages/pyvisa/resources/messagebased.py", line 157, in write_raw
File "/home/superman/.local/lib/python3.8/site-packages/pyvisa/resources/resource.py", line 190, in session
pyvisa.errors.InvalidSession: Invalid session handle. The resource might be closed.
我想正在发生的事情是 pyvisa 在__del__
我的对象的方法被调用之前被“删除”。我怎样才能防止这种情况?我如何告诉 Python pyvisa 对于Instrument
类的对象是“重要的”,所以在所有对象都被销毁之前它不会被卸载?