[Asterisk-code-review] sip to pjsip: Enable python3 compatibility. (asterisk[master])

Alexander Traud asteriskteam at digium.com
Wed Apr 18 02:30:57 CDT 2018


Alexander Traud has uploaded this change for review. ( https://gerrit.asterisk.org/8805


Change subject: sip_to_pjsip: Enable python3 compatibility.
......................................................................

sip_to_pjsip: Enable python3 compatibility.

The script remains compatible with Python 2.7 but now also works with
Python 3.3 and newer; to ease the migration from chan_sip to chan_pjsip.

ASTERISK-27811

Change-Id: I59cc6b52a1a89777eebcf25b3023bdf93babf835
---
M contrib/scripts/sip_to_pjsip/astconfigparser.py
M contrib/scripts/sip_to_pjsip/astdicts.py
M contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
M contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
M contrib/scripts/sip_to_pjsip/sqlconfigparser.py
5 files changed, 66 insertions(+), 62 deletions(-)



  git pull ssh://gerrit.asterisk.org:29418/asterisk refs/changes/05/8805/1

diff --git a/contrib/scripts/sip_to_pjsip/astconfigparser.py b/contrib/scripts/sip_to_pjsip/astconfigparser.py
index dc79e80..949acdb 100644
--- a/contrib/scripts/sip_to_pjsip/astconfigparser.py
+++ b/contrib/scripts/sip_to_pjsip/astconfigparser.py
@@ -49,7 +49,7 @@
         """
         Use self.id as means of determining equality
         """
-        return cmp(self.id, other.id)
+        return (self.id > other.id) - (self.id < other.id)
 
     def __eq__(self, other):
         """
@@ -445,7 +445,7 @@
             with open(filename, 'rt') as config_file:
                 self._read(config_file, sect)
         except IOError:
-            print "Could not open file ", filename, " for reading"
+            print("Could not open file " + filename + " for reading")
 
     def _read(self, config_file, sect):
         """Parse configuration information from the config_file"""
@@ -490,4 +490,4 @@
                 with open(config_file, 'wt') as fp:
                     self.write(fp)
             except IOError:
-                print "Could not open file ", config_file, " for writing"
+                print("Could not open file " + config_file + " for writing")
diff --git a/contrib/scripts/sip_to_pjsip/astdicts.py b/contrib/scripts/sip_to_pjsip/astdicts.py
index ae63075..39cab98 100644
--- a/contrib/scripts/sip_to_pjsip/astdicts.py
+++ b/contrib/scripts/sip_to_pjsip/astdicts.py
@@ -3,10 +3,12 @@
 # copied from http://code.activestate.com/recipes/576693/
 
 try:
-    from thread import get_ident as _get_ident
+    from threading import get_ident as _get_ident
 except ImportError:
-    from dummy_thread import get_ident as _get_ident
-
+    try:
+        from thread import get_ident as _get_ident
+    except ImportError:
+        from dummy_thread import get_ident as _get_ident
 try:
     from _abcoll import KeysView, ValuesView, ItemsView
 except ImportError:
@@ -267,11 +269,11 @@
 
     def __setitem__(self, key, val, i=None):
         if key not in self:
-#            print "__setitem__ key = ", key, " val = ", val
+#            print("__setitem__ key = " + key + " val = " + val)
             OrderedDict.__setitem__(
                 self, key, val if isinstance(val, list) else [val])
             return
-#        print "inserting key = ", key, " val = ", val
+#        print("inserting key = " + key + " val = " + val)
         vals = self[key]
         if i is None:
             i = len(vals)
diff --git a/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py b/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
index 9f7d991..e72d75a 100755
--- a/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
+++ b/contrib/scripts/sip_to_pjsip/sip_to_pjsip.py
@@ -1,9 +1,11 @@
-#!/usr/bin/python
+#!/usr/bin/env python
 
 import optparse
 import socket
-import urlparse  # Python 2.7 required for Literal IPv6 Addresses
-
+try:
+    from urllib.parse import urlparse
+except ImportError:
+    from urlparse import urlparse # Python 2.7 required for Literal IPv6 Addresses
 import astdicts
 import astconfigparser
 
@@ -90,32 +92,32 @@
         return _merge_codec_value
 
     if key == 'allow':
-	    try:
-		disallow = sip.get(section, 'disallow')[0]
-		if disallow == 'all':
-		    #don't inherit
-                    for i in sip.get(section, 'allow'):
-		        set_value(key, i, section, pjsip, nmapped, type)
-	        else:
-		    merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
-	    except LookupError:
-	        print "lookup error"
-		merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
-		return
+        try:
+            disallow = sip.get(section, 'disallow')[0]
+            if disallow == 'all':
+                #don't inherit
+                for i in sip.get(section, 'allow'):
+                    set_value(key, i, section, pjsip, nmapped, type)
+            else:
+                merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
+        except LookupError:
+            print("lookup error")
+            merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
+            return
     elif key == 'disallow':
-	    try:
-		allow = sip.get(section, 'allow')[0]
-		if allow == 'all':
-		    #don't inherit
-                    for i in sip.get(section, 'disallow'):
-		        set_value(key, i, section, pjsip, nmapped, type)
-	        else:
-		    merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
-	    except LookupError:
-		merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
-		return
+        try:
+            allow = sip.get(section, 'allow')[0]
+            if allow == 'all':
+                #don't inherit
+                for i in sip.get(section, 'disallow'):
+                    set_value(key, i, section, pjsip, nmapped, type)
+            else:
+                merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
+        except LookupError:
+            merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
+            return
     else:
-	merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
+        merge_value(key, val, section, pjsip, nmapped, type, section_to, key_to)
 
 
 def non_mapped(nmapped):
@@ -164,7 +166,7 @@
         try:
              val = sip.get('general', 't38pt_udptl')[0]
         except LookupError:
-	     return
+           return
 
     ec = 'none'
     if 'yes' in val:
@@ -291,7 +293,7 @@
 
     # Literal IPv6 (like [::]), IPv4, or hostname
     # does not work for IPv6 without brackets; case catched above
-    url = urlparse.urlparse('sip://' + host)
+    url = urlparse('sip://' + host)
 
     if port_key:
         try:
@@ -435,8 +437,7 @@
 ###############################################################################
 
 # options in pjsip.conf on an endpoint that have no sip.conf equivalent:
-# type, 100rel, trust_id_outbound, aggregate_mwi,
-# connected_line_method
+# type, 100rel, trust_id_outbound, aggregate_mwi, connected_line_method
 
 # known sip.conf peer keys that can be mapped to a pjsip.conf section/key
 peer_map = [
@@ -591,7 +592,7 @@
 
     # Literal IPv6 (like [::]), IPv4, or hostname
     # does not work for IPv6 without brackets; case catched above
-    url = urlparse.urlparse('sip://' + addr)
+    url = urlparse('sip://' + addr)
     # TODO Does not compress IPv6, for example 0:0:0:0:0:0:0:0 should get [::]
     return (url.hostname, url.port)
 
@@ -839,11 +840,11 @@
         method = sip.multi_get('general', ['tlsclientmethod',
                                            'sslclientmethod'])[0]
         if section != 'transport-' + protocol + '6':  # print only once
-            print 'In chan_sip, you specified the TLS version. With chan_sip,' \
+            print('In chan_sip, you specified the TLS version. With chan_sip,' \
                   ' this was just for outbound client connections. In' \
                   ' chan_pjsip, this value is for client and server. Instead,' \
                   ' consider not to specify \'tlsclientmethod\' for chan_sip' \
-                  ' and \'method = sslv23\' for chan_pjsip.'
+                  ' and \'method = sslv23\' for chan_pjsip.')
     except LookupError:
         """
         OpenSSL emerged during the 90s. SSLv2 and SSLv3 were the only
@@ -1246,7 +1247,7 @@
             pjsip.write(fp)
 
     except IOError:
-        print "Could not open file ", filename, " for writing"
+        print("Could not open file " + filename + " for writing")
 
 ###############################################################################
 
@@ -1277,11 +1278,11 @@
     sip_filename, pjsip_filename = cli_options()
     # configuration parser for sip.conf
     sip = astconfigparser.MultiOrderedConfigParser()
-    print 'Please, report any issue at:'
-    print '    https://issues.asterisk.org/'
-    print 'Reading', sip_filename
+    print('Please, report any issue at:')
+    print('    https://issues.asterisk.org/')
+    print('Reading ' + sip_filename)
     sip.read(sip_filename)
-    print 'Converting to PJSIP...'
+    print('Converting to PJSIP...')
     pjsip, non_mappings = convert(sip, pjsip_filename, dict(), False)
-    print 'Writing', pjsip_filename
+    print('Writing ' + pjsip_filename)
     write_pjsip(pjsip_filename, pjsip, non_mappings)
diff --git a/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py b/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
index d93bca5..71ddd45 100755
--- a/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
+++ b/contrib/scripts/sip_to_pjsip/sip_to_pjsql.py
@@ -1,6 +1,5 @@
-#!/usr/bin/python
+#!/usr/bin/env python
 
-from sip_to_pjsip import cli_options
 from sip_to_pjsip import convert
 import sip_to_pjsip
 import optparse
@@ -18,7 +17,7 @@
             pjsip.write(fp)
 
     except IOError:
-        print "Could not open file ", filename, " for writing"
+        print("Could not open file " + filename + " for writing")
 
 def cli_options():
     """
@@ -70,12 +69,12 @@
     sip = sqlconfigparser.SqlConfigParser(table)
     sip_to_pjsip.sip = sip
     sip.connect(user,password,host,port,database)
-    print 'Please, report any issue at:'
-    print '    https://issues.asterisk.org/'
-    print 'Reading', sip_filename
+    print('Please, report any issue at:')
+    print('    https://issues.asterisk.org/')
+    print('Reading ' + sip_filename)
     sip.read(sip_filename)
-    print 'Converting to PJSIP realtime sql...'
+    print('Converting to PJSIP realtime sql...')
     pjsip, non_mappings = convert(sip, pjsip_filename, dict(), False)
-    print 'Writing', pjsip_filename
+    print('Writing ' + pjsip_filename)
     write_pjsip(pjsip_filename, pjsip, non_mappings)
 
diff --git a/contrib/scripts/sip_to_pjsip/sqlconfigparser.py b/contrib/scripts/sip_to_pjsip/sqlconfigparser.py
index e87224f..1480da0 100644
--- a/contrib/scripts/sip_to_pjsip/sqlconfigparser.py
+++ b/contrib/scripts/sip_to_pjsip/sqlconfigparser.py
@@ -1,6 +1,11 @@
 from astconfigparser import MultiOrderedConfigParser
 
-import MySQLdb
+try:
+    import pymysql as MySQLdb
+    MySQLdb.install_as_MySQLdb()
+except ImportError:
+    import MySQLdb
+
 import traceback
 
 class SqlConfigParser(MultiOrderedConfigParser):
@@ -61,9 +66,6 @@
         """Write configuration information out to a file"""
         try:
             self.write_dicts(config_file, self._sections)
-        except Exception,e:
-                print "Could not open file ", config_file, " for writing"
+        except:
+                print("Could not open file " + config_file + " for writing")
                 traceback.print_exc()
-
-
-

-- 
To view, visit https://gerrit.asterisk.org/8805
To unsubscribe, visit https://gerrit.asterisk.org/settings

Gerrit-Project: asterisk
Gerrit-Branch: master
Gerrit-MessageType: newchange
Gerrit-Change-Id: I59cc6b52a1a89777eebcf25b3023bdf93babf835
Gerrit-Change-Number: 8805
Gerrit-PatchSet: 1
Gerrit-Owner: Alexander Traud <pabstraud at compuserve.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.digium.com/pipermail/asterisk-code-review/attachments/20180418/b8015b6f/attachment-0001.html>


More information about the asterisk-code-review mailing list