Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup pyvisa exception handler?

Tags:

python

visa

I try to use python 3 and pyvisa 1.8 to communicate with GPIB devices.

but how to distinguish different type of excptions.

For example:

try:
  visa.ResourceManager().open_resources('COM1')
exception visa.VisaIOError:
  <some code>

when open fails, it generate a general exception VisaIOError, but how can I know, is the port busy or the port does not exist or something else?

like:

try:
  visa.ResourceManager().open_resources('COM1')
exception <1>:
  # device busy
exception <2>:
  # device does not exist
exception ...

what should I right on position <1><2> and so on to catch different type of exceptions?

Thanks

like image 416
heyutu Avatar asked Jul 29 '26 07:07

heyutu


1 Answers

Visa can also raise ValueErrors and AttributeError if you somehow give it bad data. I think it can raise IOError, though I've never seen that happen.

But yes, it mostly raises VisaIOError.

Some things you can do to get more information about an exception are:

_rm = visa.ResourceManager()
try:
    _rm.open_resources('COM1')
exception visa.VisaIOError as e:
    print(e.args)
    print(_rm.last_status)
    print(_rm.visalib.last_status)

You can compare these status codes with various constants from visa.constants.StatusCode

if _rm.last_status == visa.constants.StatusCode.error_resource_busy:
     print("The port is busy!")

last_status and visalib.last_status sometimes give the same status code - but sometimes they don't, so you should probably check both of them.

Note that I instantiate ResourceManager. You don't have to, but there are things you can do with an instance that you can't with the class, plus if you give it a short name it's less typing.

like image 107
Jeanne Pindar Avatar answered Jul 31 '26 21:07

Jeanne Pindar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!