Mercurial > ~darius > hgwebdir.cgi > pyinst
changeset 56:91b476ebc0f2
Run through 2to3
author | Daniel O'Connor <doconnor@gsoft.com.au> |
---|---|
date | Tue, 08 Dec 2020 14:00:45 +1030 |
parents | ad5942d22f78 |
children | 19045ad9f5f5 |
files | anritsu_ms2034a_example.py datafile.py find.py plotss.py rpc.py rs_fsp7_example.py rs_fsp7_noisetest.py rsib.py sitesurvey.py tek2024b_example.py usb488.py vxi_11.py |
diffstat | 12 files changed, 141 insertions(+), 142 deletions(-) [+] |
line wrap: on
line diff
--- a/anritsu_ms2034a_example.py Tue Dec 08 13:59:05 2020 +1030 +++ b/anritsu_ms2034a_example.py Tue Dec 08 14:00:45 2020 +1030 @@ -33,7 +33,7 @@ def test(r): # ID instrument r.write('*IDN?') - print "ID is " + r.read(5) + print("ID is " + r.read(5)) # XXX: Don't do this, on this device it resets the ethernet settings (duuuh) # Reset to defaults
--- a/datafile.py Tue Dec 08 13:59:05 2020 +1030 +++ b/datafile.py Tue Dec 08 14:00:45 2020 +1030 @@ -17,10 +17,10 @@ try: self.opts[key] = int(value) - except exceptions.ValueError, e: + except exceptions.ValueError as e: try: self.opts[key] = float(value) - except exceptions.ValueError, e: + except exceptions.ValueError as e: self.opts[key] = value def __getitem__(self, k):
--- a/find.py Tue Dec 08 13:59:05 2020 +1030 +++ b/find.py Tue Dec 08 14:00:45 2020 +1030 @@ -4,6 +4,7 @@ import getopt import numpy import sys +from functools import reduce if __name__ == "__main__": opts, args = getopt.getopt(sys.argv[1:], "e:hm:s") @@ -13,13 +14,13 @@ dostats = False for o, a in opts: if o == "-h": - print """Find data files with certain characteristics + print("""Find data files with certain characteristics %s [-h] [-e exp] [-m min] [-s] file [file ..] exp Limit to experiment tag exp min Find files with power greater than min -s Print stats about files -""" +""") elif o == "-e": exptag = a elif o == "-m": @@ -27,16 +28,16 @@ elif o == "-s": dostats = True else: - print "Unknown option " + o + print("Unknown option " + o) sys.exit(1) if len(args) == 0: - print "Need at least one file to analyse" + print("Need at least one file to analyse") sys.exit(1) minfiles = [] if dostats: - print "%-50s %7s %7s %7s (dBm)" % ("Name", "Min", "Mean", "Max") + print("%-50s %7s %7s %7s (dBm)" % ("Name", "Min", "Mean", "Max")) for fn in args: dfile = datafile.DataFile(fn) @@ -48,12 +49,12 @@ minfiles.append(fn) if dostats: - print "%-50s %7.2f %7.2f %7.2f" % (fn, dfile.powers.min(), dfile.powers.mean(), dfile.powers.max()) + print("%-50s %7.2f %7.2f %7.2f" % (fn, dfile.powers.min(), dfile.powers.mean(), dfile.powers.max())) if minlev != None: if dostats: - print "" - print "Files with any sample exceeding %.2f dBm:" % (minlev) + print("") + print("Files with any sample exceeding %.2f dBm:" % (minlev)) for fn in minfiles: - print fn + print(fn)
--- a/plotss.py Tue Dec 08 13:59:05 2020 +1030 +++ b/plotss.py Tue Dec 08 14:00:45 2020 +1030 @@ -32,7 +32,7 @@ if __name__ == "__main__": if len(sys.argv) < 2: - print "Need at least one file to plot" + print("Need at least one file to plot") sys.exit(1) for fn in sys.argv[1:]:
--- a/rpc.py Tue Dec 08 13:59:05 2020 +1030 +++ b/rpc.py Tue Dec 08 14:00:45 2020 +1030 @@ -101,11 +101,11 @@ def unpack_callheader(self): xid = self.unpack_uint(xid) temp = self.unpack_enum() - if temp <> CALL: - raise BadRPCFormat, 'no CALL but ' + `temp` + if temp != CALL: + raise BadRPCFormat('no CALL but ' + repr(temp)) temp = self.unpack_uint() - if temp <> RPCVERSION: - raise BadRPCVerspion, 'bad RPC version ' + `temp` + if temp != RPCVERSION: + raise BadRPCVerspion('bad RPC version ' + repr(temp)) prog = self.unpack_uint() vers = self.unpack_uint() proc = self.unpack_uint() @@ -117,39 +117,35 @@ def unpack_replyheader(self): xid = self.unpack_uint() mtype = self.unpack_enum() - if mtype <> REPLY: - raise RuntimeError, 'no REPLY but ' + `mtype` + if mtype != REPLY: + raise RuntimeError('no REPLY but ' + repr(mtype)) stat = self.unpack_enum() if stat == MSG_DENIED: stat = self.unpack_enum() if stat == RPC_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() - raise RuntimeError, \ - 'MSG_DENIED: RPC_MISMATCH: ' + `low, high` + raise RuntimeError('MSG_DENIED: RPC_MISMATCH: ' + repr((low, high))) if stat == AUTH_ERROR: stat = self.unpack_uint() - raise RuntimeError, \ - 'MSG_DENIED: AUTH_ERROR: ' + `stat` - raise RuntimeError, 'MSG_DENIED: ' + `stat` - if stat <> MSG_ACCEPTED: - raise RuntimeError, \ - 'Neither MSG_DENIED nor MSG_ACCEPTED: ' + `stat` + raise RuntimeError('MSG_DENIED: AUTH_ERROR: ' + repr(stat)) + raise RuntimeError('MSG_DENIED: ' + repr(stat)) + if stat != MSG_ACCEPTED: + raise RuntimeError('Neither MSG_DENIED nor MSG_ACCEPTED: ' + repr(stat)) verf = self.unpack_auth() stat = self.unpack_enum() if stat == PROG_UNAVAIL: - raise RuntimeError, 'call failed: PROG_UNAVAIL' + raise RuntimeError('call failed: PROG_UNAVAIL') if stat == PROG_MISMATCH: low = self.unpack_uint() high = self.unpack_uint() - raise RuntimeError, \ - 'call failed: PROG_MISMATCH: ' + `low, high` + raise RuntimeError('call failed: PROG_MISMATCH: ' + repr((low, high))) if stat == PROC_UNAVAIL: - raise RuntimeError, 'call failed: PROC_UNAVAIL' + raise RuntimeError('call failed: PROC_UNAVAIL') if stat == GARBAGE_ARGS: - raise RuntimeError, 'call failed: GARBAGE_ARGS' - if stat <> SUCCESS: - raise RuntimeError, 'call failed: ' + `stat` + raise RuntimeError('call failed: GARBAGE_ARGS') + if stat != SUCCESS: + raise RuntimeError('call failed: ' + repr(stat)) return xid, verf # Caller must get procedure-specific part of reply @@ -200,7 +196,7 @@ offset, hh = divmod(hh + offset, 24) d = d + offset _unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0)) - print "Unix epoch:", time.ctime(_unix_epoch) + print("Unix epoch:", time.ctime(_unix_epoch)) return _unix_epoch @@ -226,7 +222,7 @@ def makesocket(self): # This MUST be overridden - raise RuntimeError, 'makesocket not defined' + raise RuntimeError('makesocket not defined') def connsocket(self): # Override this if you don't want/need a connection @@ -245,7 +241,7 @@ #print "make_call() args = " + str(args) # Don't normally override this (but see Broadcast) if pack_func is None and args is not None: - raise TypeError, 'non-null args with null pack_func' + raise TypeError('non-null args with null pack_func') #print "packed args" self.start_call(proc) if pack_func: @@ -270,7 +266,7 @@ def do_call(self): # This MUST be overridden - raise RuntimeError, 'do_call not defined' + raise RuntimeError('do_call not defined') def mkcred(self): # Override this to use more powerful credentials @@ -297,7 +293,7 @@ def sendfrag_with_timeout(sock, last, frag, timeout_seconds=None): x = len(frag) - if last: x = x | 0x80000000L + if last: x = x | 0x80000000 header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) block=header+frag @@ -307,7 +303,7 @@ if _select and timeout_seconds: rlist, wlist, xlist=_select([],[sock],[], timeout_seconds) if not wlist: - raise EOFError, "Blocked write in sendfrag()" + raise EOFError("Blocked write in sendfrag()") nsent+=sock.send(block[nsent:]) def recvfrag_with_timeout(sock, timeout_seconds=None): @@ -316,14 +312,14 @@ #print "Selecting with timeout...", timeout_seconds rlist, wlist, xlist=_select([sock],[],[], timeout_seconds) if not rlist: - raise EOFError, "No header at all in recvfrag()" + raise EOFError("No header at all in recvfrag()") header = sock.recv(4) if len(header) < 4: raise EOFError - x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \ + x = int(ord(header[0]))<<24 | ord(header[1])<<16 | \ ord(header[2])<<8 | ord(header[3]) - last = ((x & 0x80000000L) != 0) + last = ((x & 0x80000000) != 0) n = int(x & 0x7fffffff) frag='' @@ -333,7 +329,7 @@ #print "Selecting with timeout...", timeout_seconds rlist, wlist, xlist=_select([sock],[],[], timeout_seconds) if not rlist: - raise EOFError, "No data after header in recvfrag()" + raise EOFError("No data after header in recvfrag()") frag += sock.recv(n-len(frag)) return last, frag @@ -361,16 +357,17 @@ if last_resv_port_tried == None: import os last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) - for i in range(last_resv_port_tried, LAST) + \ - range(FIRST, last_resv_port_tried): + for i in list(range(last_resv_port_tried, LAST)) + \ + list(range(FIRST, last_resv_port_tried)): last_resv_port_tried = i try: sock.bind((host, i)) return last_resv_port_tried - except socket.error, (errno, msg): - if errno <> 114: - raise socket.error, (errno, msg) - raise RuntimeError, 'can\'t assign reserved port' + except socket.error as xxx_todo_changeme: + (errno, msg) = xxx_todo_changeme.args + if errno != 114: + raise socket.error(errno, msg) + raise RuntimeError('can\'t assign reserved port') # Client using TCP to a specific port @@ -389,10 +386,10 @@ u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: + if xid != self.lastxid: # Can't really happen since this is TCP... - raise RuntimeError, 'wrong xid in reply ' + `xid` + \ - ' instead of ' + `self.lastxid` + raise RuntimeError('wrong xid in reply ' + repr(xid) + \ + ' instead of ' + repr(self.lastxid)) # Client using UDP to a specific port @@ -408,7 +405,7 @@ try: from select import select except ImportError: - print 'WARNING: select not found, RPC may hang' + print('WARNING: select not found, RPC may hang') select = None BUFSIZE = 8192 # Max UDP buffer size timeout = 1 @@ -419,7 +416,7 @@ r, w, x = select(r, w, x, timeout) if self.sock not in r: count = count - 1 - if count < 0: raise RuntimeError, 'timeout' + if count < 0: raise RuntimeError('timeout') if timeout < 25: timeout = timeout *2 ## print 'RESEND', timeout, count self.sock.send(call) @@ -428,7 +425,7 @@ u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: + if xid != self.lastxid: ## print 'BAD xid' continue break @@ -455,7 +452,7 @@ def make_call(self, proc, args, pack_func, unpack_func): if pack_func is None and args is not None: - raise TypeError, 'non-null args with null pack_func' + raise TypeError('non-null args with null pack_func') self.start_call(proc) if pack_func: pack_func(args) @@ -464,7 +461,7 @@ try: from select import select except ImportError: - print 'WARNING: select not found, broadcast will hang' + print('WARNING: select not found, broadcast will hang') select = None BUFSIZE = 8192 # Max UDP buffer size (for reply) replies = [] @@ -484,7 +481,7 @@ u = self.unpacker u.reset(reply) xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: + if xid != self.lastxid: ## print 'BAD xid' continue reply = unpack_func() @@ -627,7 +624,7 @@ port = pmap.Getport((prog, vers, IPPROTO_TCP, 0)) pmap.close() if port == 0: - raise RuntimeError, 'program not registered' + raise RuntimeError('program not registered') RawTCPClient.__init__(self, host, prog, vers, port) @@ -640,7 +637,7 @@ port = pmap.Getport((prog, vers, IPPROTO_UDP, 0)) pmap.close() if port == 0: - raise RuntimeError, 'program not registered' + raise RuntimeError('program not registered') RawUDPClient.__init__(self, host, prog, vers, port) @@ -713,11 +710,11 @@ xid = self.unpacker.unpack_uint() self.packer.pack_uint(xid) temp = self.unpacker.unpack_enum() - if temp <> CALL: + if temp != CALL: return None # Not worthy of a reply self.packer.pack_uint(REPLY) temp = self.unpacker.unpack_uint() - if temp <> RPCVERSION: + if temp != RPCVERSION: self.packer.pack_uint(MSG_DENIED) self.packer.pack_uint(RPC_MISMATCH) self.packer.pack_uint(RPCVERSION) @@ -726,17 +723,17 @@ self.packer.pack_uint(MSG_ACCEPTED) self.packer.pack_auth((AUTH_NULL, make_auth_null())) prog = self.unpacker.unpack_uint() - if prog <> self.prog: + if prog != self.prog: self.packer.pack_uint(PROG_UNAVAIL) return self.packer.get_buf() vers = self.unpacker.unpack_uint() - if vers <> self.vers: + if vers != self.vers: self.packer.pack_uint(PROG_MISMATCH) self.packer.pack_uint(self.vers) self.packer.pack_uint(self.vers) return self.packer.get_buf() proc = self.unpacker.unpack_uint() - methname = 'handle_' + `proc` + methname = 'handle_' + repr(proc) try: meth = getattr(self, methname) except AttributeError: @@ -768,7 +765,7 @@ def makesocket(self): # This MUST be overridden - raise RuntimeError, 'makesocket not defined' + raise RuntimeError('makesocket not defined') def bindsocket(self): # Override this to bind to a different port (e.g. reserved) @@ -786,13 +783,13 @@ mapping = self.prog, self.vers, self.prot, self.port p = TCPPortMapperClient(self.host) if not p.Set(mapping): - raise RuntimeError, 'register failed' + raise RuntimeError('register failed') def unregister(self): mapping = self.prog, self.vers, self.prot, self.port p = TCPPortMapperClient(self.host) if not p.Unset(mapping): - raise RuntimeError, 'unregister failed' + raise RuntimeError('unregister failed') def makesocket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -810,8 +807,8 @@ call = recvrecord(sock) except EOFError: break - except socket.error, msg: - print 'socket error:', msg + except socket.error as msg: + print('socket error:', msg) break reply = self.handle(call) if reply is not None: @@ -852,13 +849,13 @@ mapping = self.prog, self.vers, self.prot, self.port p = UDPPortMapperClient(self.host) if not p.Set(mapping): - raise RuntimeError, 'register failed' + raise RuntimeError('register failed') def unregister(self): mapping = self.prog, self.vers, self.prot, self.port p = UDPPortMapperClient(self.host) if not p.Unset(mapping): - raise RuntimeError, 'unregister failed' + raise RuntimeError('unregister failed') def makesocket(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -871,7 +868,7 @@ def session(self): call, host_port = self.sock.recvfrom(8192) reply = self.handle(call) - if reply <> None: + if reply != None: self.sock.sendto(reply, host_port) @@ -882,11 +879,11 @@ list = pmap.Dump() list.sort() for prog, vers, prot, port in list: - print prog, vers, - if prot == IPPROTO_TCP: print 'tcp', - elif prot == IPPROTO_UDP: print 'udp', - else: print prot, - print port + print(prog, vers, end=' ') + if prot == IPPROTO_TCP: print('tcp', end=' ') + elif prot == IPPROTO_UDP: print('udp', end=' ') + else: print(prot, end=' ') + print(port) # Test program for broadcast operation -- dump everybody's portmapper status @@ -899,7 +896,7 @@ bcastaddr = '<broadcast>' def rh(reply, fromaddr): host, port = fromaddr - print host + '\t' + `reply` + print(host + '\t' + repr(reply)) pmap = BroadcastUDPPortMapperClient(bcastaddr) pmap.set_reply_handler(rh) pmap.set_timeout(5) @@ -917,21 +914,21 @@ def handle_1(self): arg = self.unpacker.unpack_string() self.turn_around() - print 'RPC function 1 called, arg', `arg` + print('RPC function 1 called, arg', repr(arg)) self.packer.pack_string(arg + arg) # s = S('', 0x20000000, 1, 0) try: s.unregister() - except RuntimeError, msg: - print 'RuntimeError:', msg, '(ignored)' + except RuntimeError as msg: + print('RuntimeError:', msg, '(ignored)') s.register() - print 'Service started...' + print('Service started...') try: s.loop() finally: s.unregister() - print 'Service interrupted.' + print('Service interrupted.') def testclt(): @@ -945,9 +942,9 @@ self.packer.pack_string, \ self.unpacker.unpack_string) c = C(host, 0x20000000, 1) - print 'making call...' + print('making call...') reply = c.call_1('hello, world, ') - print 'call returned', `reply` + print('call returned', repr(reply)) def testclt2(): import sys @@ -959,7 +956,7 @@ self.packer.pack_string, \ self.unpacker.unpack_string) c = C(host, 0x20000000, 1) - print 'making call...' + print('making call...') reply = c.call_1('hello, world, ') - print 'call returned', `reply` + print('call returned', repr(reply))
--- a/rs_fsp7_example.py Tue Dec 08 13:59:05 2020 +1030 +++ b/rs_fsp7_example.py Tue Dec 08 14:00:45 2020 +1030 @@ -33,7 +33,7 @@ def test(r): # ID instrument r.write('*IDN?') - print "ID is " + r.read(5) + print("ID is " + r.read(5)) # Reset to defaults r.write("*RST") @@ -56,7 +56,7 @@ # Wait up to 10 seconds for it to be done r.write("*OPC?") opc = scpi.getdata(r.read(10), int) - print "OPC - %d" % (opc) + print("OPC - %d" % (opc)) # Set peak excursion r.write("CALC:MARK:PEXC 6DB") @@ -64,7 +64,7 @@ r.write("CALC:MARK:FUNC:TOI ON") r.write("CALC:MARK:FUNC:TOI:RES?") toi = scpi.getdata(r.read(1)) - print "Result = %.2f" % (toi) + print("Result = %.2f" % (toi)) # Set data format r.write("FORM REAL,32")
--- a/rs_fsp7_noisetest.py Tue Dec 08 13:59:05 2020 +1030 +++ b/rs_fsp7_noisetest.py Tue Dec 08 14:00:45 2020 +1030 @@ -119,10 +119,10 @@ return nf def donoisetest(r, enr): - print "Acquiring with noise off.." + print("Acquiring with noise off..") setnoise(r, False) off = getnoise(r) - print "Acquiring with noise on.." + print("Acquiring with noise on..") setnoise(r, True) on = getnoise(r) return off, on, calcnf(enr, off, on) @@ -159,7 +159,7 @@ # ID instrument r.write('*IDN?') - print "ID is " + r.read(5) + print("ID is " + r.read(5)) # Setup parameters setup(r, freq, options.span, options.sweeps, options.bw) @@ -167,18 +167,18 @@ r.write("INIT:CONT OFF") nfs = [] - print "Centre: %.1f Mhz, Span %.1f Mhz, Input %.1f MHz, BW %.1f kHz, %d sweeps, ENR %.2f dB" % (freq / 1e6, options.span / 1e6, options.input / 1e6, options.bw / 1e3, options.sweeps, enr) + print("Centre: %.1f Mhz, Span %.1f Mhz, Input %.1f MHz, BW %.1f kHz, %d sweeps, ENR %.2f dB" % (freq / 1e6, options.span / 1e6, options.input / 1e6, options.bw / 1e3, options.sweeps, enr)) while options.repeat == None or options.repeat > 0: off, on, nf = donoisetest(r, enr) - print "Off %.3f dBm/Hz, on %.3f dBm/Hz, NF %.2f dB" % (off, on, nf) + print("Off %.3f dBm/Hz, on %.3f dBm/Hz, NF %.2f dB" % (off, on, nf)) nfs.append(nf) if options.repeat == None: - print "Press enter to perform a new measurement" + print("Press enter to perform a new measurement") sys.stdin.readline() else: options.repeat -= 1 if len(nfs) > 1: nfs = numpy.array(nfs) - print "NF min: %.1f dBm/Hz, max: %.1f dBm/Hz, avg: %.1f dBm/hz, stddev: %.1f" % ( - nfs.min(), nfs.max(), nfs.sum() / len(nfs), numpy.std(nfs)) + print("NF min: %.1f dBm/Hz, max: %.1f dBm/Hz, avg: %.1f dBm/hz, stddev: %.1f" % ( + nfs.min(), nfs.max(), nfs.sum() / len(nfs), numpy.std(nfs)))
--- a/rsib.py Tue Dec 08 13:59:05 2020 +1030 +++ b/rsib.py Tue Dec 08 14:00:45 2020 +1030 @@ -142,7 +142,7 @@ raise exceptions.IOError("Unexpected Msg ID 0x%02x" % (ord(rx[4]))) if ord(rx[5]) != 0: - print "Mystery byte %d != 0" % (ord(rx[5])) + print("Mystery byte %d != 0" % (ord(rx[5]))) # Fetch the actual reply now we know the length reply = '' while len(reply) < rxlen: @@ -190,4 +190,4 @@ elif rx == '\x00\x00\x00\x00\xa0\x64\x07': return True else: - raise exceptions.IOError("Unknown SRQ byte sequence - " + str(map(ord, rx))) + raise exceptions.IOError("Unknown SRQ byte sequence - " + str(list(map(ord, rx))))
--- a/sitesurvey.py Tue Dec 08 13:59:05 2020 +1030 +++ b/sitesurvey.py Tue Dec 08 14:00:45 2020 +1030 @@ -26,7 +26,7 @@ # import calendar -import ConfigParser +import configparser import datetime import exceptions import numpy @@ -57,10 +57,10 @@ try: self.opts[k] = int(v) - except exceptions.ValueError, e: + except exceptions.ValueError as e: try: self.opts[k] = float(v) - except exceptions.ValueError, e: + except exceptions.ValueError as e: self.opts[k] = v if self.recurrence == None: @@ -127,7 +127,7 @@ return soonestexp, soonestdly def getsweep(inst, conf): - print " Sending configuration" + print(" Sending configuration") for k in conf: #time.sleep(0.3) @@ -138,16 +138,16 @@ rconf = inst.dumpconf() fstart = rconf['fstart'] fstop = rconf['fstop'] - print " Configuration is " + str(rconf) + print(" Configuration is " + str(rconf)) - print " Fetching trace" + print(" Fetching trace") yaxis = inst.gettrace() xaxis = numpy.arange(fstart, fstop, (fstop - fstart) / yaxis.shape[0]) return xaxis, yaxis, rconf def savesweep(fname, exp, x, y): - print " Saving to " + fname + print(" Saving to " + fname) f = open(fname, 'wb') for k in exp: f.write("%s %s\n" % (k.upper(), str(exp[k]))) @@ -162,30 +162,30 @@ if __name__ == '__main__': # Read in config file(s) - conf = ConfigParser.SafeConfigParser(defaults) - r = conf.read(map(lambda a: os.path.join(a, confname), confpaths)) + conf = configparser.SafeConfigParser(defaults) + r = conf.read([os.path.join(a, confname) for a in confpaths]) if len(r) == 0: - print "Unable to find any configuration file(s)" + print("Unable to find any configuration file(s)") sys.exit(1) if not conf.has_section('general'): - print "Configuration file doesn't have a 'general' section" + print("Configuration file doesn't have a 'general' section") sys.exit(1) if not conf.has_option('general', 'url'): - print "Configuration file doesn't have a 'url' option in the 'general' section" + print("Configuration file doesn't have a 'url' option in the 'general' section") sys.exit(1) if not conf.has_option('general', 'type'): - print "Configuration file doesn't have a 'type' option in the 'general' section" + print("Configuration file doesn't have a 'type' option in the 'general' section") sys.exit(1) if not conf.has_option('general', 'sequence'): - print "Configuration file doesn't have a 'sequence' option in the 'general' section" + print("Configuration file doesn't have a 'sequence' option in the 'general' section") sys.exit(1) if not conf.has_option('general', 'fname'): - print "Configuration file doesn't have a 'fname' option in the 'general' section" + print("Configuration file doesn't have a 'fname' option in the 'general' section") sys.exit(1) if conf.has_option('general', 'ampcal'): @@ -209,11 +209,11 @@ fnamefmt = conf.get('general', 'fname') # Connect to the instrument - print "Connecting to " + url + print("Connecting to " + url) con = scpi.instURL(url) con.write("*IDN?") idn = con.read() - print "Instrument is a " + idn + print("Instrument is a " + idn) # Get class for this instrument & instantiate it inst = specan.getInst(insttype)(con) @@ -225,11 +225,11 @@ # Sleep if necessary dly = total_seconds(dly) if dly > 1: - print "Sleeping for %.1f seconds" % (dly) + print("Sleeping for %.1f seconds" % (dly)) time.sleep(dly) # Run it - print "--> Running experiment " + str(exp) + print("--> Running experiment " + str(exp)) freqs, power, opts = getsweep(inst, exp.opts) # Adjust power based on amplifier and antenna calibration @@ -250,14 +250,14 @@ extras = { 'timestamp' : exp.last_run, 'tag' : exp.name, } - opts = dict(opts.items() + extras.items()) + opts = dict(list(opts.items()) + list(extras.items())) fmtextras = { 'timestamp_hex' : '%08x' % (tsepoch), 'timestamp_dec' : '%d' % (tsepoch), 'fstart_mhz' : '%.1f' % (float(opts['fstart']) / 1e6), 'fstop_mhz' : '%.1f' % (float(opts['fstop']) / 1e6), } - fmtopts = dict(opts.items() + fmtextras.items()) + fmtopts = dict(list(opts.items()) + list(fmtextras.items())) fname = fnamefmt % fmtopts # Save data
--- a/tek2024b_example.py Tue Dec 08 13:59:05 2020 +1030 +++ b/tek2024b_example.py Tue Dec 08 14:00:45 2020 +1030 @@ -33,7 +33,7 @@ def test(u): u.write("*IDN?") - print "IDN reports " + u.read() + print("IDN reports " + u.read()) # Set data format to 16 bit big endian signed u.write("DATA:ENC RIB") @@ -48,12 +48,12 @@ # Fetch channel scale u.write("CH1:SCALE?") vscale = float(u.read(1).split()[1]) - print "Channel 1 scale is %.2f volts/div" % (vscale) + print("Channel 1 scale is %.2f volts/div" % (vscale)) # Fetch horizontal scale u.write("HOR:MAIN:SCALE?") hscale = scpi.getdata(u.read()) - print "Horizontal scale is %f nsec/div" % (hscale * 1e9) + print("Horizontal scale is %f nsec/div" % (hscale * 1e9)) # Make sure the previous commands have been executed u.write("*WAI") @@ -63,7 +63,7 @@ then = time.time() result = u.read(1.0) now = time.time() - print "CURVE read took %f milliseconds" % ((now - then) * 1000.0) + print("CURVE read took %f milliseconds" % ((now - then) * 1000.0)) # Parse data ary = scpi.bindecode(result, dtype = numpy.dtype('>h')) @@ -77,6 +77,6 @@ if __name__ == "__main__": u = usb488.USB488Device() - print "Found device" + print("Found device") test(u)
--- a/usb488.py Tue Dec 08 13:59:05 2020 +1030 +++ b/usb488.py Tue Dec 08 14:00:45 2020 +1030 @@ -36,6 +36,7 @@ # import usb +from functools import reduce # # The usual SCPI commands are wrapped before being sent. @@ -115,7 +116,7 @@ # class and then open, however in that case you can't # find the endpoint number which seems pretty useless # unless you want to hard code everything. - for confidx in xrange(len(dev.configurations)): + for confidx in range(len(dev.configurations)): for iface in dev.configurations[confidx].interfaces: for altif in iface: # Check if this is a USB488 capable interface @@ -165,7 +166,7 @@ # Required for 488.2 devices, optional otherwise if self.intrep == None: - print "Can't find interrupt endpoint" + print("Can't find interrupt endpoint") # Data from the scope (mandatory) if self.bulkinep == None: @@ -192,7 +193,7 @@ def write(self, data): """Send data (string) to the instrument""" - orddata = map(ord, data) + orddata = list(map(ord, data)) # The device needs a \n at the end, enfore this if orddata[-1] != '\n': orddata += [ord('\n')] @@ -254,7 +255,7 @@ #print "Sending " + str(pkt) wrote = self.handle.bulkWrite(self.bulkoutep, pkt, _timeout) if wrote != len(pkt): - print "Short write, got %d, expected %d" % (wrote, len(pkt)) + print("Short write, got %d, expected %d" % (wrote, len(pkt))) #print "Reading.." read = self.handle.bulkRead(self.bulkinep, datalen, _timeout) @@ -275,7 +276,7 @@ break # Stringify result for easier consumption - result = reduce(lambda x, y: x+y, map(chr, data)) + result = reduce(lambda x, y: x+y, list(map(chr, data))) # Trim off \n if present if result[-1] == '\n': result = result[0:-1] @@ -293,7 +294,7 @@ # This is a reasonable proxy.. try: self.handle.getString(self.dev.iManufacturer, 100) - except USBError, e: + except USBError as e: return False return True
--- a/vxi_11.py Tue Dec 08 13:59:05 2020 +1030 +++ b/vxi_11.py Tue Dec 08 14:00:45 2020 +1030 @@ -22,7 +22,7 @@ def close_all_connections(): "disconnect and close out all vxi_11 connections created here, even if their object references have been lost" - for wobj in connection_dict.keys(): + for wobj in list(connection_dict.keys()): name, wconn=connection_dict[wobj] conn=wconn() #dereference weak ref if conn is not None: @@ -55,10 +55,10 @@ "notconnected": "Device not connected"} def identify_vxi_11_error(self, error): - if self.vxi_11_errors.has_key(error): - return `error`+": "+self.vxi_11_errors[error] + if error in self.vxi_11_errors: + return repr(error)+": "+self.vxi_11_errors[error] else: - return `error`+": Unknown error code" + return repr(error)+": Unknown error code" def __init__(self, code, **other_info): @@ -170,7 +170,7 @@ if level <= self.debug_level: if file is None: file=sys.stderr - print >> file, self.device_name, message + print(self.device_name, message, file=file) def fancy_log_error(self, message, level=debug_error, file=None): if level <= self.debug_level: @@ -178,8 +178,8 @@ level_str=("**INFO*****", "**ERROR****", "**WARNING**", "**DEBUG****")[level] if file is None: file=sys.stderr - print >> file, time.asctime().strip(), '\t', level_str, '\t', self.shortname, '\t', \ - message.replace('\n','\n\t** ').replace('\r','\n\t** ') + print(time.asctime().strip(), '\t', level_str, '\t', self.shortname, '\t', \ + message.replace('\n','\n\t** ').replace('\r','\n\t** '), file=file) def log_error(self, message, level=debug_error, file=None): "override log_error() for sending messages to special places or formatting differently" @@ -273,7 +273,7 @@ if err and self.raise_on_err: e=_VXI_11_enumerated_exceptions #common, correctable exceptions - if e.has_key(err): + if err in e: raise e[err](err) #raise these exceptions explicitly else: raise VXI_11_Error(err) #raise generic VXI_11 exception