Robert Leftwich avatar Robert Leftwich committed d63cb27

Backward and forward compatibility changes to cover Python 2.6 to 3.2

Comments (0)

Files changed (8)

keyring/backend.py

 
 Keyring Backend implementations
 """
-
 import getpass
 import os
 import sys
 import base64
-import StringIO
 import copy
 import ConfigParser
 import cPickle
 import codecs
+try:
+    import StringIO
+except ImportError:
+    # handle py3 move
+    import io
+    StringIO = io.StringIO
+
+try:
+    import ConfigParser
+except ImportError:
+    # handle py3 rename
+    import configparser as ConfigParser
+ 
 
 from keyring.util.escape import escape as escape_for_ini
 import keyring.util.escape
         """
         try:
             self.keyring_impl.password_set(service, username, password)
-        except OSError, e:
+        except (OSError,):
+            e = sys.exc_info()[1]
             raise PasswordSetError(e.message)
 
 class OSXKeychain(_ExtensionKeyring):
 
     @staticmethod
     def _compound_name(username, service):
-        return u'%(username)s@%(service)s' % vars()
+        return keyring.util.escape.u('%(username)s@%(service)s') % vars()
 
     def get_password(self, service, username):
         # first attempt to get the password under the service name
                 Type=self.win32cred.CRED_TYPE_GENERIC,
                 TargetName=target,
             )
-        except self.pywintypes.error, e:
+        except (self.pywintypes.error,):
+            e = sys.exc_info()[1]
             if e.winerror == 1168 and e.funcname == 'CredRead': # not found
                 return None
             raise

keyring/backends/win32_crypto.py

      WinDLL, c_void_p, WINFUNCTYPE, cast, create_string_buffer, \
      c_char_p, byref, memmove
 
+from keyring.util.escape import u
 
 # Crypto API ctypes bindings
 
     blobout = DATA_BLOB()
 
     if not CryptProtectData(byref(blobin),
-                            u'python-keyring-lib.win32crypto',
+                            u('python-keyring-lib.win32crypto'),
                             None, None, None,
                             CRYPTPROTECT_UI_FORBIDDEN,
                             byref(blobout)):
     blobout = DATA_BLOB()
 
     if not CryptUnprotectData(byref(blobin),
-                              u'python-keyring-lib.win32crypto',
+                              u('python-keyring-lib.win32crypto'),
                               None, None, None,
                               CRYPTPROTECT_UI_FORBIDDEN,
                               byref(blobout)):
                 backend = keyring.core.load_keyring(opts.keyring_path,
                                                     opts.keyring_backend)
                 keyring.set_keyring(backend)
-            except Exception, e:
+            except (Exception,):
                 # Tons of things can go wrong here:
                 #   ImportError when using "fjkljfljkl"
                 #   AttributeError when using "os.path.bar"
                 #   TypeError when using "__builtins__.str"
                 # So, we play on the safe side, and catch everything.
+                e = sys.exc_info()[1]
                 self.parser.error("Unable to load specified keyring: %s" % e)
 
 
         This mostly exists to ease the testing process.
         """
 
-        print password
+        print >> sys.stdout, password
 
 
 def main(argv=None):

keyring/tests/test_backend.py

 
 created by Kang Zhang 2009-07-14
 """
-
 import base64
 import codecs
 import cPickle
     import unittest
 
 import keyring.backend
+from keyring.util import escape
 
 from keyring.tests import mocks
 
 ALPHABET = string.ascii_letters + string.digits
 DIFFICULT_CHARS = string.whitespace + string.punctuation
-UNICODE_CHARS = u"""κόσμεНа берегу пустынных волнSîne klâwen durh die wolken sint
-geslagen, er stîget ûf mit grôzer kraft"""
+UNICODE_CHARS = escape.u("""κόσμεНа берегу пустынных волнSîne klâwen durh die 
+wolken sint geslagen, er stîget ûf mit grôzer kraft""")
 
 class ImportKiller(object):
     "Context manager to make an import of a given name or names fail."
     def tearDown(self):
         try:
             os.unlink(self.tmp_keyring_file)
-        except OSError, e:
+        except (OSError,):
+            e = sys.exc_info()[1]
             if e.errno != 2: # No such file or directory
                 raise
 
         for cred in self.credentials_created:
             try:
                 self.keyring.delete_password(*cred)
-            except Exception, e:
+            except (Exception,):
+                e = sys.exc_info()[1]
                 print >> sys.stderr, e
 
     def init_keyring(self):

keyring/tests/test_cli.py

 """
 
 import os.path
-import unittest
+try:
+    # Python < 2.7 annd Python >= 3.0 < 3.1
+    import unittest2 as unittest
+except ImportError:
+    import unittest
 
 from keyring import cli
 import keyring.backend

keyring/tests/test_core.py

 
 Created by Kang Zhang on 2009-08-09
 """
-import unittest
+try:
+    # Python < 2.7 annd Python >= 3.0 < 3.1
+    import unittest2 as unittest
+except ImportError:
+    import unittest
 import os
 import sys
 import tempfile

keyring/tests/test_util.py

 """
 
 
-import unittest
+try:
+    # Python < 2.7 annd Python >= 3.0 < 3.1
+    import unittest2 as unittest
+except ImportError:
+    import unittest
 
 from keyring.util import escape
 
     def test_escape_unescape(self):
         self.check_escape_unescape("aaaa")
         self.check_escape_unescape("aaaa bbbb cccc")
-        self.check_escape_unescape(u"Zażółć gęślą jaźń")
+        self.check_escape_unescape(escape.u("Zażółć gęślą jaźń"))
         self.check_escape_unescape("(((P{{{{'''---; ;; '\"|%^")
 
     def test_low_byte(self):

keyring/util/escape.py

 import string
 import re
 import sys
+        
+# True if we are running on Python 3.
+# taken from six.py
+PY3 = sys.version_info[0] == 3
+
+# allow use of unicode literals
+if PY3:
+    def u(s):
+        return s
+    def unichr(c):
+        return chr(c)
+else:
+    def u(s):
+        return unicode(s, "unicode_escape")
 
 LEGAL_CHARS = (
     getattr(string, 'letters', None) # Python 2
         ESCAPE_FMT.replace('%02X', '(?P<code>[0-9A-F]{2})').encode('ascii')
     )
     return re_esc.sub(_unescape_code, value.encode('ascii')).decode('utf-8')
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.