#!/usr/bin/env python3 version = '0.02 / 2023-01-29' import pyvisa, sys, cgi, cgitb, string, os from pathlib import Path from contextlib import contextmanager #use this to avoid libgpib "invalid descriptor" errors to stdout @contextmanager def _no_stderr(): orig_stderr = os.dup(2) dev_null = os.open(os.devnull, os.O_WRONLY) os.dup2(dev_null, 2) os.close(dev_null) yield os.dup2(orig_stderr, 2) os.close(orig_stderr) form = cgi.FieldStorage() instr_address = form.getvalue('instr') scpi_command = form.getvalue('scpi') if form.getvalue('scan') == "yes": scan_instruments = True else: scan_instruments = False my_url = "/cgi-bin/"+Path(__file__).name include_file = os.path.dirname(os.path.realpath(__file__))+"/scpi.include" print('Content-type:text/html\n\n'\ 'Direct SCPI commands\n'\ '

Direct SCPI commands

') ########## IF NO INSTRUMENT WAS SELECTED, PRESENT A CHOOSER ########## if not instr_address: print('

Select instrument:

') instrument_list = [] if os.path.isfile(include_file): file1=open(include_file, "r") lines=file1.readlines() file1.close() for x in lines: x=x.strip() if x: instrument_list+=((x+" "),) if scan_instruments: with _no_stderr(): rm = pyvisa.ResourceManager() scanned_list = rm.list_resources() #scanned_list = rm.list_resources('?*') if(len(scanned_list)>0): for x in scanned_list: instrument_list+=((x+" "),) #instrument_list += scanned_list if len(instrument_list)==0: print('No instruments found

') else: print('
') for x in instrument_list: print('
') print('
') print('
 Scan for instruments
'\ '') print('

Enter instrument ID manually:

') print('
  
') ########## IF AN INSTRUMENT WAS SELECTED, ASK FOR A COMMAND ########## else: print('

Instrument selected:

'+instr_address+'

') print('
') print('

Enter command:

') print('
') print('SCPI command:

') print('
') ########## IF A COMMAND WAS GIVEN, PROCESS IT AND SHOW RESULTS ########## print('

Instrument response:

') if scpi_command: err = "" response = "" rm = pyvisa.ResourceManager() try: instr = rm.open_resource(instr_address) except pyvisa.errors.VisaIOError: err = "IO error opening device" if not err: try: instr.write(scpi_command) except pyvisa.errors.VisaIOError: err = "IO error writing device" if not err: try: response = instr.read_raw(1024) #response = b'Pflaab\x01\x02\x03Blah' #response = b'' except pyvisa.errors.VisaIOError: err = "IO error reading device" answer = "" n = 0 for x in response: if chr(x).isprintable(): answer += chr(x) n += 1 else: answer += '<'+hex(x)[2:].zfill(2).upper()+'>' n += 4 if n >= 80: answer += "\n" n = 0 if err: print('('+err+')

') elif not answer: print('(none)

') else: print('
')
      print(answer)
      print('
') print('

Direct SCPI command interface ('+Path(__file__).name\ +') ver. '+version+' by Uuki OH2GVB
Running on server '\ +os.uname()[1]+'')