python: Fix print function compatibility.
authorRussell Bryant <russell@ovn.org>
Mon, 14 Dec 2015 15:21:53 +0000 (10:21 -0500)
committerRussell Bryant <russell@ovn.org>
Tue, 12 Jan 2016 16:47:33 +0000 (11:47 -0500)
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>
Makefile.am
ofproto/ipfix-gen-entities
python/ovstest/rpcserver.py
python/ovstest/tests.py
tests/test-json.py
tests/test-jsonrpc.py
tests/test-ovsdb.py
tests/test-reconnect.py
utilities/ovs-pcap.in

index 615d456..9be2b96 100644 (file)
@@ -360,8 +360,9 @@ ALL_LOCAL += flake8-check
 # D*** -- warnings from flake8-docstrings plugin
 # H*** -- warnings from flake8 hacking plugin (custom style checks beyond PEP8)
 #   H231 Python 3.x incompatible 'except x,y:' construct
+#   H233 Python 3.x incompatible use of print operator
 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
 
 include $(srcdir)/manpages.mk
index 54951b6..a603cd1 100755 (executable)
@@ -7,6 +7,8 @@
 # notice and this notice are preserved.  This file is offered as-is,
 # without warranty of any kind.
 
+from __future__ import print_function
+
 import getopt
 import re
 import sys
@@ -48,16 +50,16 @@ class IpfixEntityHandler(xml.sax.handler.ContentHandler):
         self.current_record = dict()
 
     def startDocument(self):
-        print """\
+        print("""\
 /* IPFIX entities. */
 #ifndef IPFIX_ENTITY
 #define IPFIX_ENTITY(ENUM, ID, SIZE, NAME)
 #endif
-"""
+""")
 
     def endDocument(self):
-        print """
-#undef IPFIX_ENTITY"""
+        print("""
+#undef IPFIX_ENTITY""")
 
     def startElement(self, name, attrs):
         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['dataType'], 0)
 
-            print 'IPFIX_ENTITY(%(enumName)s, %(elementId)s, ' \
-                  '%(dataTypeSize)i, %(name)s)' % self.current_record
+            print('IPFIX_ENTITY(%(enumName)s, %(elementId)s, '
+                  '%(dataTypeSize)i, %(name)s)' % self.current_record)
             self.current_record.clear()
 
     def characters(self, content):
@@ -97,7 +99,7 @@ def print_ipfix_entity_macros(xml_file):
 
 
 def usage(name):
-    print """\
+    print("""\
 %(name)s: IPFIX entity definition generator
 Prints C macros defining IPFIX entities from the standard IANA file at
 <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:
   -h, --help                  display this help message
   -V, --version               display version information\
-""" % {'name': name}
+""" % {'name': name})
     sys.exit(0)
 
 if __name__ == '__main__':
@@ -122,7 +124,7 @@ if __name__ == '__main__':
         if key in ['-h', '--help']:
             usage()
         elif key in ['-V', '--version']:
-            print 'ipfix-gen-entities (Open vSwitch)'
+            print('ipfix-gen-entities (Open vSwitch)')
         else:
             sys.exit(0)
 
index 80b9c4e..80fc5dc 100644 (file)
@@ -16,6 +16,8 @@
 rpcserver is an XML RPC server that allows RPC client to initiate tests
 """
 
+from __future__ import print_function
+
 import exceptions
 import sys
 import xmlrpclib
@@ -357,7 +359,7 @@ def start_rpc_server(port):
     rpc_server = TestArena()
     reactor.listenTCP(port, server.Site(rpc_server))
     try:
-        print "Starting RPC server\n"
+        print("Starting RPC server\n")
         sys.stdout.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
index 108cad4..e9e2936 100644 (file)
@@ -10,6 +10,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from __future__ import print_function
+
 import math
 import time
 
@@ -28,11 +30,11 @@ def do_udp_tests(receiver, sender, tbwidth, duration, port_sizes):
 
     udpformat = '{0:>15} {1:>15} {2:>15} {3:>15} {4:>15}'
 
-    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],
                              util.bandwidth_to_string(tbwidth)))
-    print udpformat.format("Datagram Size", "Snt Datagrams", "Rcv Datagrams",
-                            "Datagram Loss", "Bandwidth")
+    print(udpformat.format("Datagram Size", "Snt Datagrams", "Rcv Datagrams",
+                            "Datagram Loss", "Bandwidth"))
 
     for size in port_sizes:
         listen_handle = NO_HANDLE
@@ -42,8 +44,8 @@ def do_udp_tests(receiver, sender, tbwidth, duration, port_sizes):
 
             listen_handle = server1.create_udp_listener(receiver[3])
             if listen_handle == NO_HANDLE:
-                print ("Server could not open UDP listening socket on port"
-                        " %u. Try to restart the server.\n" % receiver[3])
+                print("Server could not open UDP listening socket on port"
+                      " %u. Try to restart the server.\n" % receiver[3])
                 return
             send_handle = server2.create_udp_sender(
                                             (util.ip_from_cidr(receiver[2]),
@@ -61,14 +63,14 @@ def do_udp_tests(receiver, sender, tbwidth, duration, port_sizes):
                                                         snt_packets) / 100
             bwidth = (rcv_packets * size) / duration
 
-            print udpformat.format(size, snt_packets, rcv_packets,
-                          '%.2f%%' % loss, util.bandwidth_to_string(bwidth))
+            print(udpformat.format(size, snt_packets, rcv_packets,
+                          '%.2f%%' % loss, util.bandwidth_to_string(bwidth)))
         finally:
             if listen_handle != NO_HANDLE:
                 server1.close_udp_listener(listen_handle)
             if send_handle != NO_HANDLE:
                 server2.close_udp_sender(send_handle)
-    print "\n"
+    print("\n")
 
 
 def do_tcp_tests(receiver, sender, duration):
@@ -77,17 +79,17 @@ def do_tcp_tests(receiver, sender, duration):
     server2 = util.rpc_client(sender[0], sender[1])
 
     tcpformat = '{0:>15} {1:>15} {2:>15}'
-    print "TCP test from %s:%u to %s:%u (full speed)" % (sender[0], sender[1],
-                                                    receiver[0], receiver[1])
-    print tcpformat.format("Snt Bytes", "Rcv Bytes", "Bandwidth")
+    print("TCP test from %s:%u to %s:%u (full speed)" % (sender[0], sender[1],
+                                                    receiver[0], receiver[1]))
+    print(tcpformat.format("Snt Bytes", "Rcv Bytes", "Bandwidth"))
 
     listen_handle = NO_HANDLE
     send_handle = NO_HANDLE
     try:
         listen_handle = server1.create_tcp_listener(receiver[3])
         if listen_handle == NO_HANDLE:
-            print ("Server was unable to open TCP listening socket on port"
-                    " %u. Try to restart the server.\n" % receiver[3])
+            print("Server was unable to open TCP listening socket on port"
+                  " %u. Try to restart the server.\n" % receiver[3])
             return
         send_handle = server2.create_tcp_sender(util.ip_from_cidr(receiver[2]),
                                                 receiver[3], duration)
@@ -99,14 +101,14 @@ def do_tcp_tests(receiver, sender, duration):
 
         bwidth = rcv_bytes / duration
 
-        print tcpformat.format(snt_bytes, rcv_bytes,
-                               util.bandwidth_to_string(bwidth))
+        print(tcpformat.format(snt_bytes, rcv_bytes,
+                               util.bandwidth_to_string(bwidth)))
     finally:
         if listen_handle != NO_HANDLE:
             server1.close_tcp_listener(listen_handle)
         if send_handle != NO_HANDLE:
             server2.close_tcp_sender(send_handle)
-    print "\n"
+    print("\n")
 
 
 def do_l3_tests(node1, node2, bandwidth, duration, ps, type):
index 1356145..c97d46d 100644 (file)
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from __future__ import print_function
+
 import codecs
 import getopt
 import sys
@@ -21,7 +23,7 @@ import ovs.json
 
 def print_json(json):
     if type(json) in [str, unicode]:
-        print "error: %s" % json
+        print("error: %s" % json)
         return False
     else:
         ovs.json.to_stream(json, sys.stdout)
index 8ba0703..18634e6 100644 (file)
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from __future__ import print_function
+
 import argparse
 import errno
 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.exit(1)
 
-    print ovs.json.to_string(msg.to_json())
+    print(ovs.json.to_string(msg.to_json()))
 
     rpc.close()
 
index 5744fde..1042ccf 100644 (file)
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from __future__ import print_function
+
 import getopt
 import re
 import os
@@ -82,19 +84,19 @@ def do_default_data():
 def do_parse_atomic_type(type_string):
     type_json = unbox_json(ovs.json.from_string(type_string))
     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):
     type_json = unbox_json(ovs.json.from_string(type_string))
     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):
     type_json = unbox_json(ovs.json.from_string(type_string))
     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):
@@ -104,9 +106,9 @@ def do_parse_atoms(type_string, *atom_strings):
         atom_json = unbox_json(ovs.json.from_string(atom_string))
         try:
             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:
-            print e.args[0].encode("utf8")
+            print(e.args[0].encode("utf8"))
 
 
 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:
         datum_json = unbox_json(ovs.json.from_string(datum_string))
         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):
@@ -123,27 +125,27 @@ def do_sort_atoms(type_string, atom_strings):
     base = ovs.db.types.BaseType.from_json(type_json)
     atoms = [data.Atom.from_json(base, atom_json)
              for atom_json in unbox_json(ovs.json.from_string(atom_strings))]
-    print ovs.json.to_string([data.Atom.to_json(atom)
-                              for atom in sorted(atoms)])
+    print(ovs.json.to_string([data.Atom.to_json(atom)
+                              for atom in sorted(atoms)]))
 
 
 def do_parse_column(name, column_string):
     column_json = unbox_json(ovs.json.from_string(column_string))
     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'):
     default_is_root = default_is_root_string == 'true'
     table_json = unbox_json(ovs.json.from_string(table_string))
     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):
     schema_json = unbox_json(ovs.json.from_string(schema_string))
     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):
@@ -349,7 +351,7 @@ def idl_set(idl, commands, step):
             txn.abort()
             break
         elif name == "destroy":
-            print "%03d: destroy" % step
+            print("%03d: destroy" % step)
             sys.stdout.flush()
             txn.abort()
             return
@@ -484,7 +486,7 @@ def do_idl(schema_file, remote, *commands):
 
 
 def usage():
-    print """\
+    print("""\
 %(program_name)s: test utility for Open vSwitch database Python bindings
 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:
   -t, --timeout=SECS          give up after SECS seconds
   -h, --help                  display this help message\
-""" % {'program_name': ovs.util.PROGRAM_NAME}
+""" % {'program_name': ovs.util.PROGRAM_NAME})
     sys.exit(0)
 
 
index dbe266a..e291e34 100644 (file)
@@ -12,6 +12,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from __future__ import print_function
+
 import errno
 import sys
 
@@ -74,11 +76,11 @@ def do_run(arg):
     if action is None:
         pass
     elif action == ovs.reconnect.CONNECT:
-        print "  should connect"
+        print("  should connect")
     elif action == ovs.reconnect.DISCONNECT:
-        print "  should disconnect"
+        print("  should disconnect")
     elif action == ovs.reconnect.PROBE:
-        print "  should send probe"
+        print("  should send probe")
     else:
         assert False
 
@@ -92,10 +94,10 @@ def do_timeout(_):
     global now
     timeout = r.timeout(now)
     if timeout >= 0:
-        print "  advance %d ms" % timeout
+        print("  advance %d ms" % timeout)
         now += timeout
     else:
-        print "  no timeout"
+        print("  no timeout")
 
 
 def do_set_max_tries(arg):
@@ -183,7 +185,7 @@ def main():
     r = ovs.reconnect.Reconnect(now)
     r.set_name("remote")
     prev = r.get_stats(now)
-    print "### t=%d ###" % now
+    print("### t=%d ###" % now)
     old_time = now
     old_max_tries = r.get_max_tries()
     while True:
@@ -191,7 +193,7 @@ def main():
         if line == "":
             break
 
-        print line[:-1]
+        print(line[:-1])
         if line[0] == "#":
             continue
 
@@ -207,15 +209,15 @@ def main():
         commands[command](op)
 
         if old_time != now:
-            print
-            print "### t=%d ###" % now
+            print()
+            print("### t=%d ###" % now)
 
         cur = r.get_stats(now)
         diff_stats(prev, cur, now - old_time)
         prev = cur
         if r.get_max_tries() != old_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
 
index ed35fc5..ae30047 100755 (executable)
@@ -14,6 +14,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+from __future__ import print_function
+
 import binascii
 import getopt
 import struct
@@ -57,7 +59,7 @@ argv0 = sys.argv[0]
 
 
 def usage():
-    print """\
+    print("""\
 %(argv0)s: print pcap file packet data as hex
 usage: %(argv0)s FILE
 where FILE is a PCAP file.
@@ -65,7 +67,7 @@ where FILE is a PCAP file.
 The following options are also available:
   -h, --help                  display this help message
   -V, --version               display version information\
-""" % {'argv0': argv0}
+""" % {'argv0': argv0})
     sys.exit(0)
 
 if __name__ == "__main__":
@@ -81,7 +83,7 @@ if __name__ == "__main__":
             if key in ['-h', '--help']:
                 usage()
             elif key in ['-V', '--version']:
-                print "ovs-pcap (Open vSwitch) @VERSION@"
+                print("ovs-pcap (Open vSwitch) @VERSION@")
             else:
                 sys.exit(0)
 
@@ -96,7 +98,7 @@ if __name__ == "__main__":
             if packet is None:
                 break
 
-            print binascii.hexlify(packet)
+            print(binascii.hexlify(packet))
 
     except PcapException as e:
         sys.stderr.write("%s: %s\n" % (argv0, e))