Commit 11cf383f authored by Vincent Michel's avatar Vincent Michel Committed by Sebastien Petitdemange

Run 2to3 script

$ 2to3 -w .
$ 2to3 -w bin/*
$ black bin/*
parent 365d4fb5
......@@ -26,8 +26,8 @@ except gevent.Timeout:
if replied_host:
max_host_len = max([len(host) for host, port in replied_host])
format = "{0: <%d} {1}" % max_host_len
print(format.format("HOST", "PORT"))
print((format.format("HOST", "PORT")))
for host, port in sorted(replied_host):
print(format.format(host, port))
print((format.format(host, port)))
else:
print("No response!!!")
......@@ -25,7 +25,7 @@ try:
arguments = docopt.docopt(__doc__)
port = int(arguments["--port"])
except docopt.DocoptExit as e:
print e.message
print(e.message)
else:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
......
......@@ -71,7 +71,7 @@ def copy_data(zerod, zerod_index, session_name, max_nb_counter, max_nb_points):
sps.putdata(session_name, ARRAY_NAME, sps_data)
min_index = nb_points
for channel_name, channel_info in zerod_index.iteritems():
for channel_name, channel_info in zerod_index.items():
point_nb = channel_info.get("from")
if point_nb < min_index:
min_index = point_nb
......@@ -120,10 +120,10 @@ def watch_data(scan_node, session_name):
"scanno": new_scanno(),
"datafile": "bliss",
"spec": session_name,
"columnnames": zerod_index.keys()
+ [""] * (nbcounters - len(zerod_index.keys())),
"columns": len(zerod_index.keys()),
"selectedcounters": ";".join(zerod_index.keys()),
"columnnames": list(zerod_index.keys())
+ [""] * (nbcounters - len(list(zerod_index.keys()))),
"columns": len(list(zerod_index.keys())),
"selectedcounters": ";".join(list(zerod_index.keys())),
},
{},
)
......@@ -177,7 +177,7 @@ def main():
arguments = docopt.docopt(__doc__)
sessions_name = arguments["<name>"]
except docopt.DocoptExit as e:
print e.message
print(e.message)
else:
tasks = list()
for session in sessions_name:
......
......@@ -65,7 +65,7 @@ def main(host=None, user=None, passwd=None):
else:
properties[name] = [values, value]
for node in server2nodes.values():
for node in list(server2nodes.values()):
node.save()
......
......@@ -112,10 +112,10 @@ class Exporter(ExporterClient.ExporterClient):
if "\x1f" in value:
value = self.parseArray(value)
try:
value = map(int, value)
value = list(map(int, value))
except:
try:
value = map(float, value)
value = list(map(float, value))
except:
pass
else:
......@@ -163,7 +163,7 @@ class ExporterChannel:
def update(self, value=None):
if value is None:
value = self.getValue()
if isinstance(value, tuple):
if type(value) == tuple:
value = list(value)
self.value = value
......
......@@ -7,9 +7,8 @@
Copyright 2009 by European Molecular Biology Laboratory - Grenoble
"""
from __future__ import absolute_import
from warnings import warn
from StandardClient import *
from .StandardClient import *
CMD_SYNC_CALL = "EXEC"
CMD_ASNC_CALL = "ASNC"
......@@ -34,7 +33,7 @@ class ExporterClient(StandardClient):
try:
evtstr = msg[4:]
tokens = evtstr.split(PARAMETER_SEPARATOR)
self.onEvent(tokens[0], tokens[1], long(tokens[2]))
self.onEvent(tokens[0], tokens[1], int(tokens[2]))
except:
# print("Error processing event: " + str(sys.exc_info()[1]))
pass
......
This diff is collapsed.
......@@ -9,7 +9,7 @@ import sys
import time
import string
import threading
from ExporterClient import *
from .ExporterClient import *
SERVER_ADDRESS = "localhost"
SERVER_PORT = 9001
......@@ -243,7 +243,7 @@ if __name__ == "__main__":
class Microdiff(MDEvents):
def onReceivedEvent(self, name, value, timestamp):
print " Event: " + name + " = " + str(value)
print(" Event: " + name + " = " + str(value))
md = Microdiff(SERVER_ADDRESS, SERVER_PORT, PROTOCOL.STREAM, TIMEOUT, RETRIES)
md.start()
......@@ -251,6 +251,6 @@ if __name__ == "__main__":
while True:
time.sleep(1.0)
if not md.isConnected():
print "Not Connected"
print("Not Connected")
md.stop()
......@@ -108,15 +108,15 @@ class StandardClient:
try:
self.__sock__.sendto(msg, (self.server_ip, self.server_port))
except:
raise SocketError, "Socket error:" + str(sys.exc_info()[1])
raise SocketError("Socket error:" + str(sys.exc_info()[1]))
received = False
while received == False:
try:
ret = self.__sock__.recv(4096)
except socket.timeout:
raise TimeoutError, "Timeout error:" + str(sys.exc_info()[1])
raise TimeoutError("Timeout error:" + str(sys.exc_info()[1]))
except:
raise SocketError, "Socket error:" + str(sys.exc_info()[1])
raise SocketError("Socket error:" + str(sys.exc_info()[1]))
if ret[0:5] == msg_number:
received = True
ret = ret[5:]
......@@ -230,7 +230,7 @@ class StandardClient:
with gevent.Timeout(self.timeout, TimeoutError):
while self.received_msg is None:
if not self.error is None:
raise SocketError, "Socket error:" + str(self.error)
raise SocketError("Socket error:" + str(self.error))
self.msg_received_event.wait()
return self.received_msg
......@@ -254,7 +254,9 @@ class StandardClient:
@protect_from_kill
def send(self, cmd):
if self.protocol == PROTOCOL.DATAGRAM:
raise ProtocolError, "Protocol error: send command not support in datagram clients"
raise ProtocolError(
"Protocol error: send command not support in datagram clients"
)
else:
return self.__sendStream__(cmd)
......
......@@ -9,4 +9,4 @@
interface specific classes)
"""
from _gpib import *
from ._gpib import *
......@@ -347,7 +347,7 @@ class Gpib:
interface = Gpib(url="enet://gpibid00a.esrf.fr", pad=15)
"""
ENET, TANGO, TANGO_DEVICE_SERVER, PROLOGIX, LOCAL = range(5)
ENET, TANGO, TANGO_DEVICE_SERVER, PROLOGIX, LOCAL = list(range(5))
READ_BLOCK_SIZE = 64 * 1024
def __init__(self, url=None, pad=0, sad=0, timeout=1., tmo=13, eot=1, eos="\n"):
......
......@@ -45,9 +45,9 @@ def _dbg(f, name=None):
name = f.__name__
def wrap(self, *a, **k):
print "DBG: %s: enter: %s %s" % (name, ` a `, ` k `),
print("DBG: %s: enter: %s %s" % (name, repr(a), repr(k)), end=" ")
r = f(self, *a, **k)
print "exit: %s" % ` r `
print("exit: %s" % repr(r))
return r
wrap._dummy = True
......@@ -59,7 +59,7 @@ def _not_impl(name):
if "ignore_not_impl" in debug:
return None
else:
raise NotImplementedError, "%s not implemented", name
raise NotImplementedError("%s not implemented").with_traceback(name)
return _dbg(wrap, name)
......@@ -99,8 +99,8 @@ class EnetSocket(object):
if "dummy_io" in debug:
_open = lambda self: None
_send = lambda self, s: sys.stderr.write("DBG: > %s" % (` s `))
_recv = lambda self, len: raw_input("DBG: < #%s:" % (len))[:len]
_send = lambda self, s: sys.stderr.write("DBG: > %s" % (repr(s)))
_recv = lambda self, len: input("DBG: < #%s:" % (len))[:len]
_close = lambda self: None
if "io" in debug:
......@@ -395,7 +395,7 @@ class EnetLib(object):
if name[:3] == "dev":
pad = int(name[3:])
else:
raise ValueError, "configuration not yet implemented. use devX"
raise ValueError("configuration not yet implemented. use devX")
return self.ibdev(pad)
def ibdev(self, *a, **ka):
......@@ -430,16 +430,16 @@ if __name__ == "__main__":
nienet_host = "qo-hpf-gpib1.ethz.ch"
l = EnetLib(nienet_host)
ud = l.ibdev(pad=13)
print "ibrsp", l.ibrsp(ud)
print "iblines", l.iblines(ud)
print "ibtrg", l.ibtrg(ud)
print "ibask", l.ibask(ud, 1)
print "ibln 13", l.ibln(ud, 13)
print "ibln 11", l.ibln(ud, 11)
print "ibwrt", l.ibwrt(ud, "ID?;")
print "ibrd", l.ibrd(ud, 10)
print "ibwrt", l.ibwrt(ud, "SET?;")
print "ibrd", ` l.ibrd(ud, 640) `
print "ibwrt", l.ibwrt(ud, "DSTB;")
print "ibrd", ` l.ibrd(ud, 4096) `
print "ibbna", l.ibbna(ud)
print("ibrsp", l.ibrsp(ud))
print("iblines", l.iblines(ud))
print("ibtrg", l.ibtrg(ud))
print("ibask", l.ibask(ud, 1))
print("ibln 13", l.ibln(ud, 13))
print("ibln 11", l.ibln(ud, 11))
print("ibwrt", l.ibwrt(ud, "ID?;"))
print("ibrd", l.ibrd(ud, 10))
print("ibwrt", l.ibwrt(ud, "SET?;"))
print("ibrd", repr(l.ibrd(ud, 640)))
print("ibwrt", l.ibwrt(ud, "DSTB;"))
print("ibrd", repr(l.ibrd(ud, 4096)))
print("ibbna", l.ibbna(ud))
......@@ -561,7 +561,7 @@ class ModbusTcp:
modbus._connected = False
modbus._fd = None
# inform all pending requests that the socket closed
for trans in modbus._transaction.values():
for trans in list(modbus._transaction.values()):
trans.put(socket.error(errno.EPIPE, "Broken pipe"))
except ReferenceError:
pass
......@@ -158,7 +158,7 @@ class _ServerObject(object):
def __dir__(self):
result = ["zerorpc_call__"]
for name, info in self._metadata["members"].items():
for name, info in list(self._metadata["members"].items()):
if "method" in info["type"]:
result.append(name)
return result
......@@ -332,7 +332,7 @@ def Client(address, **kwargs):
stream = metadata.get("stream", False)
members = dict(_client=client)
for name, info in metadata["members"].items():
for name, info in list(metadata["members"].items()):
if name.startswith("__") and name[2:-2] in SPECIAL_METHODS:
continue
name, mtype, doc = info["name"], info["type"], info["doc"]
......
......@@ -33,7 +33,6 @@ Example::
"""
from __future__ import absolute_import
import re
import inspect
......@@ -47,17 +46,17 @@ from .exceptions import CommunicationError, CommunicationTimeout
def decode_IDN(s):
manuf, model, serial, version = map(str.strip, s.split(","))
manuf, model, serial, version = list(map(str.strip, s.split(",")))
return dict(manufacturer=manuf, model=model, serial=serial, version=version)
def __decode_Err(s):
code, desc = map(str.strip, s.split(",", 1))
code, desc = list(map(str.strip, s.split(",", 1)))
return dict(code=int(code), desc=desc[1:-1])
def __decode_ErrArray(s):
msgs = map(str.strip, s.split(","))
msgs = list(map(str.strip, s.split(",")))
result = []
for i in range(0, len(msgs), 2):
code, desc = int(msgs[i]), msgs[i + 1][1:-1]
......@@ -285,7 +284,7 @@ class Commands(object):
try:
return self._command_cache[cmd_name_u]
except KeyError:
for cmd_expr, cmd_info in self.command_expressions.items():
for cmd_expr, cmd_info in list(self.command_expressions.items()):
reg_expr = cmd_info["re"]
if reg_expr.match(cmd_name):
self._command_cache[cmd_name.upper()] = cmd_expr
......@@ -303,7 +302,7 @@ class Commands(object):
self.command_expressions.update(commands.command_expressions)
self._command_cache.update(commands._command_cache)
elif isinstance(commands, dict):
for cmd_expr, cmd in commands.items():
for cmd_expr, cmd in list(commands.items()):
self[cmd_expr] = cmd
else:
for cmd_expr, cmd in commands:
......@@ -779,7 +778,7 @@ def main(argv=None):
)
add(
"--parity",
choices=serial.PARITY_NAMES.keys(),
choices=list(serial.PARITY_NAMES.keys()),
default=serial.PARITY_NONE,
help="parity type",
)
......
......@@ -5,7 +5,6 @@
# Copyright (c) 2016 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.
from __future__ import absolute_import
__all__ = ["LocalSerial", "RFC2217", "SER2NET", "TangoSerial", "Serial"]
......@@ -397,7 +396,7 @@ class RFC2217(_BaseSerial):
self._socket.send(telnet_sub_cmd.data)
telnet_sub_cmd.data = ""
items = self.rfc2217_port_settings.values()
items = list(self.rfc2217_port_settings.values())
while 1:
self._parse_nego(telnet_cmd)
if sum(o.active for o in items) == len(items):
......@@ -490,7 +489,7 @@ class RFC2217(_BaseSerial):
elif suboption == FLOWCONTROL_RESUME:
self._remote_suspend_flow = False
else:
for item in self.rfc2217_options.values():
for item in list(self.rfc2217_options.values()):
if item.ack_option == suboption:
item.checkAnswer(value)
break
......@@ -608,7 +607,7 @@ class TangoSerial(_BaseSerial):
get_object_proxy(device).set_timeout_millis(int(timeout * 1000))
args = []
kwargs["eol"] = cnt._eol
for arg, (key, encode) in self.PAR_MAP.items():
for arg, (key, encode) in list(self.PAR_MAP.items()):
args.append(arg)
args.append(encode(self, kwargs[key]))
device.DevSerSetParameter(args)
......@@ -650,7 +649,7 @@ class TangoSerial(_BaseSerial):
class Serial:
LOCAL, RFC2217, SER2NET, TANGO = range(4)
LOCAL, RFC2217, SER2NET, TANGO = list(range(4))
def __init__(
self,
......
......@@ -117,7 +117,7 @@ class SpecChannel:
def update(self, channelValue, deleted=False, force=False):
"""Update channel's value and emit the 'valueChanged' signal."""
if isinstance(channelValue, types.DictType) and self.access1 is not None:
if isinstance(channelValue, dict) and self.access1 is not None:
if self.access1 in channelValue:
if deleted:
event.send(self, "valueChanged", (None, self.name))
......@@ -128,7 +128,7 @@ class SpecChannel:
or self.value is None
or self.value != channelValue[self.access1]
):
if isinstance(channelValue[self.access1], types.DictType):
if isinstance(channelValue[self.access1], dict):
self.value = channelValue[self.access1].copy()
else:
self.value = self._coerce(channelValue[self.access1])
......@@ -152,13 +152,11 @@ class SpecChannel:
)
return
if isinstance(self.value, types.DictType) and isinstance(
channelValue, types.DictType
):
if isinstance(self.value, dict) and isinstance(channelValue, dict):
# update dictionary
if deleted:
for key, val in channelValue.iteritems():
if isinstance(val, types.DictType):
for key, val in channelValue.items():
if isinstance(val, dict):
for k in val:
try:
del self.value[key][k]
......@@ -172,8 +170,8 @@ class SpecChannel:
except KeyError:
pass
else:
for k1, v1 in channelValue.iteritems():
if isinstance(v1, types.DictType):
for k1, v1 in channelValue.items():
if isinstance(v1, dict):
try:
self.value[k1].update(v1)
except KeyError:
......@@ -182,9 +180,7 @@ class SpecChannel:
self.value[k1] = {None: self.value[k1]}
self.value[k1].update(v1)
else:
if k1 in self.value and isinstance(
self.value[k1], types.DictType
):
if k1 in self.value and isinstance(self.value[k1], dict):
self.value[k1][None] = v1
else:
self.value[k1] = v1
......
......@@ -37,7 +37,7 @@ class wrap_errors(object):
func = self.func
try:
return func(*args, **kwargs)
except Exception, e:
except Exception as e:
return SpecClientError(e)
def __str__(self):
......@@ -70,7 +70,7 @@ class BaseSpecCommand:
self.setCommand(command)
if connection is not None:
if type(connection) in (types.UnicodeType, types.StringType):
if type(connection) in (str, bytes):
#
# connection is given in the 'host:port' form
#
......@@ -123,7 +123,7 @@ class BaseSpecCommand:
# convert args list to string args list
# it is much more convenient using .call('psvo', 12) than .call('psvo', '12')
# a possible problem will be seen in Spec
args = map(repr, args)
args = list(map(repr, args))
if func:
# macro function
......
......@@ -93,7 +93,7 @@ def rawtodictonary(rawstring):
else:
data[key] = val
else:
if keyel[0] in data and not isinstance(data[keyel[0]], types.DictType):
if keyel[0] in data and not isinstance(data[keyel[0]], dict):
data[keyel[0]] = {None: data[keyel[0]]}
try:
......@@ -109,9 +109,9 @@ def dictionarytoraw(dict):
"""Transform a Python dictionary object to the string format
expected by Spec"""
data = ""
for key, val in dict.items():
if isinstance(val, types.DictType):
for kkey, vval in val.iteritems():
for key, val in list(dict.items()):
if isinstance(val, dict):
for kkey, vval in val.items():
if kkey is None:
data += str(key) + NULL + str(vval) + NULL
else:
......@@ -231,15 +231,11 @@ class SpecMessage:
- it is a hard job guessing ARRAY_* types, we ignore this case (user has to provide a suitable datatype)
- we cannot make a difference between ERROR type and STRING type
"""
if isinstance(data, types.StringType):
if isinstance(data, bytes):
return STRING
elif isinstance(data, types.DictType):
elif isinstance(data, dict):
return ASSOC
elif (
isinstance(data, types.IntType)
or isinstance(data, types.LongType)
or isinstance(data, types.FloatType)
):
elif isinstance(data, int) or isinstance(data, int) or isinstance(data, float):
return STRING
def sendingDataString(self, data, datatype):
......@@ -509,13 +505,13 @@ class anymessage(SpecMessage):
def commandListToCommandString(cmdlist):
"""Convert a command list to a Spec command string."""
if isinstance(cmdlist, types.ListType) and len(cmdlist) > 0:
if isinstance(cmdlist, list) and len(cmdlist) > 0:
cmd = [str(cmdlist[0])]
for arg in cmdlist[1:]:
argstr = repr(arg)