[PATCH] python/osmo-python-tests[master]: Improve python3 compatibility

This is merely a historical archive of years 2008-2021, before the migration to mailman3.

A maintained and still updated list archive can be found at https://lists.osmocom.org/hyperkitty/list/gerrit-log@lists.osmocom.org/.

Max gerrit-no-reply at lists.osmocom.org
Mon Nov 27 14:56:53 UTC 2017


Review at  https://gerrit.osmocom.org/5038

Improve python3 compatibility

* use print()
* use named exception

In case of osmo_ctrl.py we can already switch to python3 as it's a
standalone script. Other scripts might be used as a libraries so leave
the shebang without modifications for now.

Change-Id: I80e5850a8978d78cda793e2192ef4bd3fd54a121
---
M osmopy/obscvty.py
M osmopy/osmo_ctrl.py
M osmopy/osmodumpdoc.py
M osmopy/osmotestconfig.py
M osmopy/osmotestvty.py
M osmopy/osmoutil.py
6 files changed, 45 insertions(+), 45 deletions(-)


  git pull ssh://gerrit.osmocom.org:29418/python/osmo-python-tests refs/changes/38/5038/1

diff --git a/osmopy/obscvty.py b/osmopy/obscvty.py
index 1e05d77..2963393 100755
--- a/osmopy/obscvty.py
+++ b/osmopy/obscvty.py
@@ -31,12 +31,12 @@
 debug_tcp_sockets = (os.getenv('OSMOPY_DEBUG_TCP_SOCKETS', '0') != '0')
 
 def cmd(what):
-    print '\n> %s' % what
+    print('\n> %s' % what)
     sys.stdout.flush()
     subprocess.call(what, shell=True)
     sys.stdout.flush()
     sys.stderr.flush()
-    print ''
+    print('')
     sys.stdout.flush()
 
 def print_used_tcp_sockets():
@@ -86,14 +86,14 @@
                     raise
                 # possibly the binary hasn't launched yet
                 if debug_tcp_sockets:
-                    print "Connecting socket failed, retrying..."
+                    print("Connecting socket failed, retrying...")
                 time.sleep(.1)
                 continue
             break
 
         if debug_tcp_sockets:
             VTYInteract.all_sockets.append(self.socket)
-            print "Socket: in %d tries, connected to %s:%d %r (%d sockets open)" % (
+            print("Socket: in %d tries, connected to %s:%d %r (%d sockets open)" % ())
                     took, self.host, self.port, self.socket,
                     len(VTYInteract.all_sockets))
         self.socket.recv(4096)
@@ -108,9 +108,9 @@
                 VTYInteract.all_sockets.remove(self.socket)
             except ValueError:
                 pass
-            print "Socket: closing %s:%d %r (%d sockets open)" % (
+            print("Socket: closing %s:%d %r (%d sockets open)" % (
                     self.host, self.port, self.socket,
-                    len(VTYInteract.all_sockets))
+                    len(VTYInteract.all_sockets)))
         self.socket.close()
         self.socket = None
 
@@ -248,7 +248,7 @@
 
         if loud:
             if res != results:
-                print "Rec: %s\nExp: %s" % (res, results)
+                print("Rec: %s\nExp: %s" % (res, results))
 
         return res == results
 
diff --git a/osmopy/osmo_ctrl.py b/osmopy/osmo_ctrl.py
index 003f100..b8a6c94 100755
--- a/osmopy/osmo_ctrl.py
+++ b/osmopy/osmo_ctrl.py
@@ -1,8 +1,8 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 # -*- mode: python-mode; py-indent-tabs-mode: nil -*-
 """
 /*
- * Copyright (C) 2016 sysmocom s.f.m.c. GmbH
+ * Copyright (C) 2016-2017 sysmocom s.f.m.c. GmbH
  *
  * All Rights Reserved
  *
@@ -22,6 +22,7 @@
  */
 """
 
+# FIXME: use argparse instead of deprecated optparse
 from optparse import OptionParser
 from osmopy.osmo_ipa import Ctrl
 import socket
@@ -30,7 +31,7 @@
 
 def connect(host, port):
         if verbose:
-                print "Connecting to host %s:%i" % (host, port)
+                print("Connecting to host %s:%i" % (host, port))
 
         sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sck.setblocking(1)
@@ -57,13 +58,13 @@
         """
         try:
                 data = sck.recv(1024, fl)
-        except socket.error as (s_errno, strerror):
+        except socket.error as _:
                 return False
         if len(data) != 0:
                 tail = data
                 while True:
                         (head, tail) = Ctrl().split_combined(tail)
-                        print "Got message:", Ctrl().rem_header(head)
+                        print("Got message:", Ctrl().rem_header(head))
                         if len(tail) == 0:
                                 break
                 return True
@@ -103,18 +104,18 @@
                 if len(args) < 2:
                         parser.error("Set requires var and value arguments")
                 _leftovers(sock, socket.MSG_DONTWAIT)
-                print "Got message:", set_var(sock, args[0], ' '.join(args[1:]))
+                print("Got message:", set_var(sock, args[0], ' '.join(args[1:])))
 
         if options.cmd_get:
                 if len(args) != 1:
                         parser.error("Get requires the var argument")
                 _leftovers(sock, socket.MSG_DONTWAIT)
                 (a, _, _) = do_set_get(sock, args[0])
-                print "Got message:", a
+                print("Got message:", a)
 
         if options.monitor:
                 while True:
                         if not _leftovers(sock, 0):
-                                print "Connection is gone."
+                                print("Connection is gone.")
                                 break
         sock.close()
diff --git a/osmopy/osmodumpdoc.py b/osmopy/osmodumpdoc.py
index 2464b05..796b2b5 100644
--- a/osmopy/osmodumpdoc.py
+++ b/osmopy/osmodumpdoc.py
@@ -21,7 +21,7 @@
     out = open(filename, 'w')
     out.write(xml)
     out.close()
-    print 'generated %r' % filename
+    print('generated %r' % filename)
 
 
 """Dump the config of all the apps.
@@ -40,22 +40,22 @@
 
     for app in apps:
         appname = app[3]
-        print "Starting app for %s" % appname
+        print("Starting app for %s" % appname)
         proc = None
         cmd = [app[1], "-c", os.path.join(confpath, configs[appname][0])]
-        print 'cd', os.path.abspath(os.path.curdir), ';', ' '.join(cmd)
+        print('cd', os.path.abspath(os.path.curdir), ';', ' '.join(cmd))
         try:
             proc = subprocess.Popen(cmd, stdin=None, stdout=None)
         except OSError as e:  # Probably a missing binary
-            print >> sys.stderr, e
-            print >> sys.stderr, "Skipping app %s" % appname
+            print(e, file=sys.stderr)
+            print("Skipping app %s" % appname, file=sys.stderr)
             failures += 1
         else:
             try:
                 dump_doc(app[2], app[0], 'doc/%s_vty_reference.xml' % appname)
                 successes += 1
             except IOError:  # Generally a socket issue
-                print >> sys.stderr, "%s: couldn't connect, skipping" % appname
+                print("%s: couldn't connect, skipping" % appname, file=sys.stderr)
                 failures += 1
         finally:
             osmoutil.end_proc(proc)
@@ -90,7 +90,7 @@
     num_fails, num_sucs = dump_configs(
         osmoappdesc.apps, osmoappdesc.app_configs, confpath)
     if num_fails > 0:
-        print >> sys.stderr, "Warning: Skipped %s apps" % num_fails
+        print("Warning: Skipped %s apps" % num_fails, file=sys.stderr)
         if 0 == num_sucs:
-            print >> sys.stderr, "Nothing run, wrong working dir? Set with -w"
+            print("Nothing run, wrong working dir? Set with -w", file=sys.stderr)
     sys.exit(num_fails)
diff --git a/osmopy/osmotestconfig.py b/osmopy/osmotestconfig.py
index 2132c43..7c0715f 100644
--- a/osmopy/osmotestconfig.py
+++ b/osmopy/osmotestconfig.py
@@ -52,7 +52,7 @@
     try:
         cmd = app_desc[1].split(' ') + [ "-c", config]
         if verbose:
-            print "Verifying %s, test %s" % (' '.join(cmd), run_test.__name__)
+            print("Verifying %s, test %s" % (' '.join(cmd), run_test.__name__))
 
         proc = osmoutil.popen_devnull(cmd)
         end = app_desc[2]
@@ -61,10 +61,10 @@
         ret = run_test(vty)
 
     except IOError as se:
-        print >> sys.stderr, "Failed to verify %s" % ' '.join(cmd)
-        print >> sys.stderr, "Current directory: %s" % os.getcwd()
-        print >> sys.stderr, "Error was %s" % se
-        print >> sys.stderr, "Config was\n%s" % open(config).read()
+        print("Failed to verify %s" % ' '.join(cmd), file=sys.stderr)
+        print("Current directory: %s" % os.getcwd(), file=sys.stderr)
+        print("Error was %s" % se, file=sys.stderr)
+        print("Config was\n%s" % open(config).read(), file=sys.stderr)
         raise se
 
     finally:
@@ -125,9 +125,8 @@
 
             all_errs.append(err_lines)
 
-            print >> sys.stderr, \
-                "Documentation error (missing docs): \n%s\n%s\n" % (
-                cmd_line, '\n'.join(err_lines))
+            print("Documentation error (missing docs): \n%s\n%s\n" % (
+                cmd_line, '\n'.join(err_lines)), file=sys.stderr)
 
     return (len(all_errs), all_errs)
 
@@ -157,7 +156,7 @@
             if config in app_configs[app]:
                 found = True
         if not found:
-            print >> sys.stderr, "Warning: %s is not being tested" % config
+            print("Warning: %s is not being tested" % config, file=sys.stderr)
 
 
 def test_all_apps(apps, app_configs, tmpdir="writtenconfig", verbose=True,
@@ -166,7 +165,7 @@
     errors = 0
     for app in apps:
         if not app_exists(app):
-            print >> sys.stderr, "Skipping app %s (not found)" % app[1]
+            print("Skipping app %s (not found)" % app[1], file=sys.stderr)
             continue
 
         configs = app_configs[app[3]]
@@ -178,7 +177,7 @@
         remove_tmpdir(tmpdir)
 
     if errors:
-        print >> sys.stderr, "ERRORS: %d" % errors
+        print("ERRORS: %d" % errors, file=sys.stderr)
     return errors
 
 
diff --git a/osmopy/osmotestvty.py b/osmopy/osmotestvty.py
index e513c05..52c5f22 100644
--- a/osmopy/osmotestvty.py
+++ b/osmopy/osmotestvty.py
@@ -36,11 +36,11 @@
             osmo_vty_cmd[cfi] = os.path.join(confpath, osmo_vty_cmd[cfi])
 
         try:
-            print "Launch: %s from %s" % (' '.join(osmo_vty_cmd), os.getcwd())
+            print("Launch: %s from %s" % (' '.join(osmo_vty_cmd), os.getcwd()))
             self.proc = osmoutil.popen_devnull(osmo_vty_cmd)
         except OSError:
-            print >> sys.stderr, "Current directory: %s" % os.getcwd()
-            print >> sys.stderr, "Consider setting -b"
+            print("Current directory: %s" % os.getcwd(), file=sys.stderr)
+            print("Consider setting -b", file=sys.stderr)
 
         appstring = osmoappdesc.vty_app[2]
         appport = osmoappdesc.vty_app[0]
@@ -94,9 +94,9 @@
     osmoappdesc = osmoutil.importappconf_or_quit(confpath, "osmoappdesc",
                                                  args.p)
 
-    print "confpath %s, workdir %s" % (confpath, workdir)
+    print("confpath %s, workdir %s" % (confpath, workdir))
     os.chdir(workdir)
-    print "Running tests for specific VTY commands"
+    print("Running tests for specific VTY commands")
     suite = unittest.TestLoader().loadTestsFromTestCase(TestVTY)
     res = unittest.TextTestRunner(verbosity=verbose_level).run(suite)
     sys.exit(len(res.errors) + len(res.failures))
diff --git a/osmopy/osmoutil.py b/osmopy/osmoutil.py
index 8f0369b..86c7e3d 100755
--- a/osmopy/osmoutil.py
+++ b/osmopy/osmoutil.py
@@ -30,10 +30,10 @@
     global devnull
     if devnull is None:
         if verbose:
-            print "Opening /dev/null"
+            print("Opening /dev/null")
         devnull = open(os.devnull, 'w')
     if verbose:
-        print "Launching: PWD=%s %s" % (os.getcwd(), ' '.join([repr(c) for c in cmd]))
+        print("Launching: PWD=%s %s" % (os.getcwd(), ' '.join([repr(c) for c in cmd])))
     return subprocess.Popen(cmd, stdout=devnull, stderr=devnull)
 
 
@@ -65,9 +65,9 @@
     if proc.poll() is None:
         # termination seems to be slower than that, let's just kill
         proc.kill()
-        print "Killed child process"
+        print("Killed child process")
     elif waited_time > .002:
-        print "Terminating took %.3fs" % waited_time
+        print("Terminating took %.3fs" % waited_time)
     proc.wait()
 
 
@@ -80,9 +80,9 @@
         return importlib.import_module(confname)
     except ImportError as e:
         if p_set:
-            print >> sys.stderr, "osmoappdesc not found in %s" % dirname
+            print("osmoappdesc not found in %s" % dirname, file=sys.stderr)
         else:
-            print >> sys.stderr, "set osmoappdesc location with -p <dir>"
+            print("set osmoappdesc location with -p <dir>", file=sys.stderr)
         sys.exit(1)
 
 

-- 
To view, visit https://gerrit.osmocom.org/5038
To unsubscribe, visit https://gerrit.osmocom.org/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I80e5850a8978d78cda793e2192ef4bd3fd54a121
Gerrit-PatchSet: 1
Gerrit-Project: python/osmo-python-tests
Gerrit-Branch: master
Gerrit-Owner: Max <msuraev at sysmocom.de>



More information about the gerrit-log mailing list