2
0
mirror of https://github.com/openvswitch/ovs synced 2025-09-05 00:35:33 +00:00

python: Fix print function compatibility.

The print statement from Python 2 is a function in Python 3.  Enable
print function support for Python 2 and convert print statements to
function calls.

Enable the H233 flake8 warning.  If the hacking plugin is installed,
this will generate warnings for print statement usage not compatible
with Python 3.

  H233 Python 3.x incompatible use of print operator

Signed-off-by: Russell Bryant <russell@ovn.org>
Acked-by: Ben Pfaff <blp@ovn.org>
This commit is contained in:
Russell Bryant
2015-12-14 10:21:53 -05:00
parent f3068bff92
commit 8ea171aba0
9 changed files with 74 additions and 57 deletions

View File

@@ -360,8 +360,9 @@ ALL_LOCAL += flake8-check
# D*** -- warnings from flake8-docstrings plugin # D*** -- warnings from flake8-docstrings plugin
# H*** -- warnings from flake8 hacking plugin (custom style checks beyond PEP8) # H*** -- warnings from flake8 hacking plugin (custom style checks beyond PEP8)
# H231 Python 3.x incompatible 'except x,y:' construct # H231 Python 3.x incompatible 'except x,y:' construct
# H233 Python 3.x incompatible use of print operator
flake8-check: $(FLAKE8_PYFILES) flake8-check: $(FLAKE8_PYFILES)
$(AM_V_GEN) if flake8 $^ --select=H231 --ignore=E121,E123,E125,E126,E127,E128,E129,E131,W503,F811,D,H ${FLAKE8_FLAGS}; then touch $@; else exit 1; fi $(AM_V_GEN) if flake8 $^ --select=H231,H233 --ignore=E121,E123,E125,E126,E127,E128,E129,E131,W503,F811,D,H ${FLAKE8_FLAGS}; then touch $@; else exit 1; fi
endif endif
include $(srcdir)/manpages.mk include $(srcdir)/manpages.mk

View File

@@ -7,6 +7,8 @@
# notice and this notice are preserved. This file is offered as-is, # notice and this notice are preserved. This file is offered as-is,
# without warranty of any kind. # without warranty of any kind.
from __future__ import print_function
import getopt import getopt
import re import re
import sys import sys
@@ -48,16 +50,16 @@ class IpfixEntityHandler(xml.sax.handler.ContentHandler):
self.current_record = dict() self.current_record = dict()
def startDocument(self): def startDocument(self):
print """\ print("""\
/* IPFIX entities. */ /* IPFIX entities. */
#ifndef IPFIX_ENTITY #ifndef IPFIX_ENTITY
#define IPFIX_ENTITY(ENUM, ID, SIZE, NAME) #define IPFIX_ENTITY(ENUM, ID, SIZE, NAME)
#endif #endif
""" """)
def endDocument(self): def endDocument(self):
print """ print("""
#undef IPFIX_ENTITY""" #undef IPFIX_ENTITY""")
def startElement(self, name, attrs): def startElement(self, name, attrs):
if name in self.RECORD_FIELDS: if name in self.RECORD_FIELDS:
@@ -83,8 +85,8 @@ class IpfixEntityHandler(xml.sax.handler.ContentHandler):
self.current_record['dataTypeSize'] = self.DATA_TYPE_SIZE.get( self.current_record['dataTypeSize'] = self.DATA_TYPE_SIZE.get(
self.current_record['dataType'], 0) self.current_record['dataType'], 0)
print 'IPFIX_ENTITY(%(enumName)s, %(elementId)s, ' \ print('IPFIX_ENTITY(%(enumName)s, %(elementId)s, '
'%(dataTypeSize)i, %(name)s)' % self.current_record '%(dataTypeSize)i, %(name)s)' % self.current_record)
self.current_record.clear() self.current_record.clear()
def characters(self, content): def characters(self, content):
@@ -97,7 +99,7 @@ def print_ipfix_entity_macros(xml_file):
def usage(name): def usage(name):
print """\ print("""\
%(name)s: IPFIX entity definition generator %(name)s: IPFIX entity definition generator
Prints C macros defining IPFIX entities from the standard IANA file at Prints C macros defining IPFIX entities from the standard IANA file at
<http://www.iana.org/assignments/ipfix/ipfix.xml> <http://www.iana.org/assignments/ipfix/ipfix.xml>
@@ -107,7 +109,7 @@ where XML is the standard IANA XML file defining IPFIX entities
The following options are also available: The following options are also available:
-h, --help display this help message -h, --help display this help message
-V, --version display version information\ -V, --version display version information\
""" % {'name': name} """ % {'name': name})
sys.exit(0) sys.exit(0)
if __name__ == '__main__': if __name__ == '__main__':
@@ -122,7 +124,7 @@ if __name__ == '__main__':
if key in ['-h', '--help']: if key in ['-h', '--help']:
usage() usage()
elif key in ['-V', '--version']: elif key in ['-V', '--version']:
print 'ipfix-gen-entities (Open vSwitch)' print('ipfix-gen-entities (Open vSwitch)')
else: else:
sys.exit(0) sys.exit(0)

View File

@@ -16,6 +16,8 @@
rpcserver is an XML RPC server that allows RPC client to initiate tests rpcserver is an XML RPC server that allows RPC client to initiate tests
""" """
from __future__ import print_function
import exceptions import exceptions
import sys import sys
import xmlrpclib import xmlrpclib
@@ -357,7 +359,7 @@ def start_rpc_server(port):
rpc_server = TestArena() rpc_server = TestArena()
reactor.listenTCP(port, server.Site(rpc_server)) reactor.listenTCP(port, server.Site(rpc_server))
try: try:
print "Starting RPC server\n" print("Starting RPC server\n")
sys.stdout.flush() sys.stdout.flush()
# If this server was started from ovs-test client then we must flush # If this server was started from ovs-test client then we must flush
# STDOUT so that client would know that server is ready to accept # STDOUT so that client would know that server is ready to accept

View File

@@ -10,6 +10,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import math import math
import time import time
@@ -31,8 +33,8 @@ def do_udp_tests(receiver, sender, tbwidth, duration, port_sizes):
print("UDP test from %s:%u to %s:%u with target bandwidth %s" % print("UDP test from %s:%u to %s:%u with target bandwidth %s" %
(sender[0], sender[1], receiver[0], receiver[1], (sender[0], sender[1], receiver[0], receiver[1],
util.bandwidth_to_string(tbwidth))) util.bandwidth_to_string(tbwidth)))
print udpformat.format("Datagram Size", "Snt Datagrams", "Rcv Datagrams", print(udpformat.format("Datagram Size", "Snt Datagrams", "Rcv Datagrams",
"Datagram Loss", "Bandwidth") "Datagram Loss", "Bandwidth"))
for size in port_sizes: for size in port_sizes:
listen_handle = NO_HANDLE listen_handle = NO_HANDLE
@@ -61,14 +63,14 @@ def do_udp_tests(receiver, sender, tbwidth, duration, port_sizes):
snt_packets) / 100 snt_packets) / 100
bwidth = (rcv_packets * size) / duration bwidth = (rcv_packets * size) / duration
print udpformat.format(size, snt_packets, rcv_packets, print(udpformat.format(size, snt_packets, rcv_packets,
'%.2f%%' % loss, util.bandwidth_to_string(bwidth)) '%.2f%%' % loss, util.bandwidth_to_string(bwidth)))
finally: finally:
if listen_handle != NO_HANDLE: if listen_handle != NO_HANDLE:
server1.close_udp_listener(listen_handle) server1.close_udp_listener(listen_handle)
if send_handle != NO_HANDLE: if send_handle != NO_HANDLE:
server2.close_udp_sender(send_handle) server2.close_udp_sender(send_handle)
print "\n" print("\n")
def do_tcp_tests(receiver, sender, duration): def do_tcp_tests(receiver, sender, duration):
@@ -77,9 +79,9 @@ def do_tcp_tests(receiver, sender, duration):
server2 = util.rpc_client(sender[0], sender[1]) server2 = util.rpc_client(sender[0], sender[1])
tcpformat = '{0:>15} {1:>15} {2:>15}' tcpformat = '{0:>15} {1:>15} {2:>15}'
print "TCP test from %s:%u to %s:%u (full speed)" % (sender[0], sender[1], print("TCP test from %s:%u to %s:%u (full speed)" % (sender[0], sender[1],
receiver[0], receiver[1]) receiver[0], receiver[1]))
print tcpformat.format("Snt Bytes", "Rcv Bytes", "Bandwidth") print(tcpformat.format("Snt Bytes", "Rcv Bytes", "Bandwidth"))
listen_handle = NO_HANDLE listen_handle = NO_HANDLE
send_handle = NO_HANDLE send_handle = NO_HANDLE
@@ -99,14 +101,14 @@ def do_tcp_tests(receiver, sender, duration):
bwidth = rcv_bytes / duration bwidth = rcv_bytes / duration
print tcpformat.format(snt_bytes, rcv_bytes, print(tcpformat.format(snt_bytes, rcv_bytes,
util.bandwidth_to_string(bwidth)) util.bandwidth_to_string(bwidth)))
finally: finally:
if listen_handle != NO_HANDLE: if listen_handle != NO_HANDLE:
server1.close_tcp_listener(listen_handle) server1.close_tcp_listener(listen_handle)
if send_handle != NO_HANDLE: if send_handle != NO_HANDLE:
server2.close_tcp_sender(send_handle) server2.close_tcp_sender(send_handle)
print "\n" print("\n")
def do_l3_tests(node1, node2, bandwidth, duration, ps, type): def do_l3_tests(node1, node2, bandwidth, duration, ps, type):

View File

@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import codecs import codecs
import getopt import getopt
import sys import sys
@@ -21,7 +23,7 @@ import ovs.json
def print_json(json): def print_json(json):
if type(json) in [str, unicode]: if type(json) in [str, unicode]:
print "error: %s" % json print("error: %s" % json)
return False return False
else: else:
ovs.json.to_stream(json, sys.stdout) ovs.json.to_stream(json, sys.stdout)

View File

@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import argparse import argparse
import errno import errno
import os import os
@@ -127,7 +129,7 @@ def do_request(name, method, params_string):
sys.stderr.write("error waiting for reply: %s\n" % os.strerror(error)) sys.stderr.write("error waiting for reply: %s\n" % os.strerror(error))
sys.exit(1) sys.exit(1)
print ovs.json.to_string(msg.to_json()) print(ovs.json.to_string(msg.to_json()))
rpc.close() rpc.close()

View File

@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import getopt import getopt
import re import re
import os import os
@@ -82,19 +84,19 @@ def do_default_data():
def do_parse_atomic_type(type_string): def do_parse_atomic_type(type_string):
type_json = unbox_json(ovs.json.from_string(type_string)) type_json = unbox_json(ovs.json.from_string(type_string))
atomic_type = ovs.db.types.AtomicType.from_json(type_json) atomic_type = ovs.db.types.AtomicType.from_json(type_json)
print ovs.json.to_string(atomic_type.to_json(), sort_keys=True) print(ovs.json.to_string(atomic_type.to_json(), sort_keys=True))
def do_parse_base_type(type_string): def do_parse_base_type(type_string):
type_json = unbox_json(ovs.json.from_string(type_string)) type_json = unbox_json(ovs.json.from_string(type_string))
base_type = ovs.db.types.BaseType.from_json(type_json) base_type = ovs.db.types.BaseType.from_json(type_json)
print ovs.json.to_string(base_type.to_json(), sort_keys=True) print(ovs.json.to_string(base_type.to_json(), sort_keys=True))
def do_parse_type(type_string): def do_parse_type(type_string):
type_json = unbox_json(ovs.json.from_string(type_string)) type_json = unbox_json(ovs.json.from_string(type_string))
type_ = ovs.db.types.Type.from_json(type_json) type_ = ovs.db.types.Type.from_json(type_json)
print ovs.json.to_string(type_.to_json(), sort_keys=True) print(ovs.json.to_string(type_.to_json(), sort_keys=True))
def do_parse_atoms(type_string, *atom_strings): def do_parse_atoms(type_string, *atom_strings):
@@ -104,9 +106,9 @@ def do_parse_atoms(type_string, *atom_strings):
atom_json = unbox_json(ovs.json.from_string(atom_string)) atom_json = unbox_json(ovs.json.from_string(atom_string))
try: try:
atom = data.Atom.from_json(base, atom_json) atom = data.Atom.from_json(base, atom_json)
print ovs.json.to_string(atom.to_json()) print(ovs.json.to_string(atom.to_json()))
except error.Error as e: except error.Error as e:
print e.args[0].encode("utf8") print(e.args[0].encode("utf8"))
def do_parse_data(type_string, *data_strings): def do_parse_data(type_string, *data_strings):
@@ -115,7 +117,7 @@ def do_parse_data(type_string, *data_strings):
for datum_string in data_strings: for datum_string in data_strings:
datum_json = unbox_json(ovs.json.from_string(datum_string)) datum_json = unbox_json(ovs.json.from_string(datum_string))
datum = data.Datum.from_json(type_, datum_json) datum = data.Datum.from_json(type_, datum_json)
print ovs.json.to_string(datum.to_json()) print(ovs.json.to_string(datum.to_json()))
def do_sort_atoms(type_string, atom_strings): def do_sort_atoms(type_string, atom_strings):
@@ -123,27 +125,27 @@ def do_sort_atoms(type_string, atom_strings):
base = ovs.db.types.BaseType.from_json(type_json) base = ovs.db.types.BaseType.from_json(type_json)
atoms = [data.Atom.from_json(base, atom_json) atoms = [data.Atom.from_json(base, atom_json)
for atom_json in unbox_json(ovs.json.from_string(atom_strings))] for atom_json in unbox_json(ovs.json.from_string(atom_strings))]
print ovs.json.to_string([data.Atom.to_json(atom) print(ovs.json.to_string([data.Atom.to_json(atom)
for atom in sorted(atoms)]) for atom in sorted(atoms)]))
def do_parse_column(name, column_string): def do_parse_column(name, column_string):
column_json = unbox_json(ovs.json.from_string(column_string)) column_json = unbox_json(ovs.json.from_string(column_string))
column = ovs.db.schema.ColumnSchema.from_json(column_json, name) column = ovs.db.schema.ColumnSchema.from_json(column_json, name)
print ovs.json.to_string(column.to_json(), sort_keys=True) print(ovs.json.to_string(column.to_json(), sort_keys=True))
def do_parse_table(name, table_string, default_is_root_string='false'): def do_parse_table(name, table_string, default_is_root_string='false'):
default_is_root = default_is_root_string == 'true' default_is_root = default_is_root_string == 'true'
table_json = unbox_json(ovs.json.from_string(table_string)) table_json = unbox_json(ovs.json.from_string(table_string))
table = ovs.db.schema.TableSchema.from_json(table_json, name) table = ovs.db.schema.TableSchema.from_json(table_json, name)
print ovs.json.to_string(table.to_json(default_is_root), sort_keys=True) print(ovs.json.to_string(table.to_json(default_is_root), sort_keys=True))
def do_parse_schema(schema_string): def do_parse_schema(schema_string):
schema_json = unbox_json(ovs.json.from_string(schema_string)) schema_json = unbox_json(ovs.json.from_string(schema_string))
schema = ovs.db.schema.DbSchema.from_json(schema_json) schema = ovs.db.schema.DbSchema.from_json(schema_json)
print ovs.json.to_string(schema.to_json(), sort_keys=True) print(ovs.json.to_string(schema.to_json(), sort_keys=True))
def print_idl(idl, step): def print_idl(idl, step):
@@ -349,7 +351,7 @@ def idl_set(idl, commands, step):
txn.abort() txn.abort()
break break
elif name == "destroy": elif name == "destroy":
print "%03d: destroy" % step print("%03d: destroy" % step)
sys.stdout.flush() sys.stdout.flush()
txn.abort() txn.abort()
return return
@@ -484,7 +486,7 @@ def do_idl(schema_file, remote, *commands):
def usage(): def usage():
print """\ print("""\
%(program_name)s: test utility for Open vSwitch database Python bindings %(program_name)s: test utility for Open vSwitch database Python bindings
usage: %(program_name)s [OPTIONS] COMMAND ARG... usage: %(program_name)s [OPTIONS] COMMAND ARG...
@@ -539,7 +541,7 @@ idl SCHEMA SERVER [?T1:C1,C2...[?T2:C1,C2,...]...] [TRANSACTION...]
The following options are also available: The following options are also available:
-t, --timeout=SECS give up after SECS seconds -t, --timeout=SECS give up after SECS seconds
-h, --help display this help message\ -h, --help display this help message\
""" % {'program_name': ovs.util.PROGRAM_NAME} """ % {'program_name': ovs.util.PROGRAM_NAME})
sys.exit(0) sys.exit(0)

View File

@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import errno import errno
import sys import sys
@@ -74,11 +76,11 @@ def do_run(arg):
if action is None: if action is None:
pass pass
elif action == ovs.reconnect.CONNECT: elif action == ovs.reconnect.CONNECT:
print " should connect" print(" should connect")
elif action == ovs.reconnect.DISCONNECT: elif action == ovs.reconnect.DISCONNECT:
print " should disconnect" print(" should disconnect")
elif action == ovs.reconnect.PROBE: elif action == ovs.reconnect.PROBE:
print " should send probe" print(" should send probe")
else: else:
assert False assert False
@@ -92,10 +94,10 @@ def do_timeout(_):
global now global now
timeout = r.timeout(now) timeout = r.timeout(now)
if timeout >= 0: if timeout >= 0:
print " advance %d ms" % timeout print(" advance %d ms" % timeout)
now += timeout now += timeout
else: else:
print " no timeout" print(" no timeout")
def do_set_max_tries(arg): def do_set_max_tries(arg):
@@ -183,7 +185,7 @@ def main():
r = ovs.reconnect.Reconnect(now) r = ovs.reconnect.Reconnect(now)
r.set_name("remote") r.set_name("remote")
prev = r.get_stats(now) prev = r.get_stats(now)
print "### t=%d ###" % now print("### t=%d ###" % now)
old_time = now old_time = now
old_max_tries = r.get_max_tries() old_max_tries = r.get_max_tries()
while True: while True:
@@ -191,7 +193,7 @@ def main():
if line == "": if line == "":
break break
print line[:-1] print(line[:-1])
if line[0] == "#": if line[0] == "#":
continue continue
@@ -207,15 +209,15 @@ def main():
commands[command](op) commands[command](op)
if old_time != now: if old_time != now:
print print()
print "### t=%d ###" % now print("### t=%d ###" % now)
cur = r.get_stats(now) cur = r.get_stats(now)
diff_stats(prev, cur, now - old_time) diff_stats(prev, cur, now - old_time)
prev = cur prev = cur
if r.get_max_tries() != old_max_tries: if r.get_max_tries() != old_max_tries:
old_max_tries = r.get_max_tries() old_max_tries = r.get_max_tries()
print " %d tries left" % old_max_tries print(" %d tries left" % old_max_tries)
old_time = now old_time = now

View File

@@ -14,6 +14,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
import binascii import binascii
import getopt import getopt
import struct import struct
@@ -57,7 +59,7 @@ argv0 = sys.argv[0]
def usage(): def usage():
print """\ print("""\
%(argv0)s: print pcap file packet data as hex %(argv0)s: print pcap file packet data as hex
usage: %(argv0)s FILE usage: %(argv0)s FILE
where FILE is a PCAP file. where FILE is a PCAP file.
@@ -65,7 +67,7 @@ where FILE is a PCAP file.
The following options are also available: The following options are also available:
-h, --help display this help message -h, --help display this help message
-V, --version display version information\ -V, --version display version information\
""" % {'argv0': argv0} """ % {'argv0': argv0})
sys.exit(0) sys.exit(0)
if __name__ == "__main__": if __name__ == "__main__":
@@ -81,7 +83,7 @@ if __name__ == "__main__":
if key in ['-h', '--help']: if key in ['-h', '--help']:
usage() usage()
elif key in ['-V', '--version']: elif key in ['-V', '--version']:
print "ovs-pcap (Open vSwitch) @VERSION@" print("ovs-pcap (Open vSwitch) @VERSION@")
else: else:
sys.exit(0) sys.exit(0)
@@ -96,7 +98,7 @@ if __name__ == "__main__":
if packet is None: if packet is None:
break break
print binascii.hexlify(packet) print(binascii.hexlify(packet))
except PcapException as e: except PcapException as e:
sys.stderr.write("%s: %s\n" % (argv0, e)) sys.stderr.write("%s: %s\n" % (argv0, e))