【发布时间】:2020-12-04 14:34:36
【问题描述】:
我正在使用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.
我猜发生的事情是在我的对象的__del__ 方法被调用之前,pyvisa 被“删除”了。我怎样才能防止这种情况?我如何告诉 Python pyvisa 对于 Instrument 类的对象是“重要的”,因此在所有对象都被销毁之前它不会被卸载?
【问题讨论】: