Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Begining move to python3 #342

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions src/gmv/blowfish.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class Blowfish:
DECRYPT = 1

# For _round()
_MODULUS = 2L ** 32
_MODULUS = 2 ** 32

# CTR constants
_BLOCK_SIZE = 8
Expand Down Expand Up @@ -528,23 +528,23 @@ def _round(self, xl):

def _demo(heading, source, encrypted, decrypted):
"""demo method """
print heading
print "\tSource: %(source)s" % {
print(heading)
print("\tSource: %(source)s" % {
'source': source,
}
print "\tEncrypted: %(encrypted)s" % {
})
print("\tEncrypted: %(encrypted)s" % {
'encrypted': encrypted,
}
print "\tDecrypted: %(decrypted)s" % {
})
print("\tDecrypted: %(decrypted)s" % {
'decrypted': decrypted,
}
print
})
print()

key = 'This is a test key'
cipher = Blowfish(key)

# Encryption processing
(xl, xr) = (123456L, 654321L)
(xl, xr) = (123456, 654321)
(cl, cr) = cipher.cipher(xl, xr, cipher.ENCRYPT)
(dl, dr) = cipher.cipher(cl, cr, cipher.DECRYPT)
_demo("Testing encryption", (xl, xr), (cl, cr), (dl, dr))
Expand All @@ -564,7 +564,7 @@ def _demo(heading, source, encrypted, decrypted):
_demo("Testing CTR logic", text, repr(crypted), decrypted)

# Test speed
print "Testing speed"
print("Testing speed")
test_strings = [''.join(("The quick brown fox jumps over the lazy dog", str(i),)) for i in xrange(1000)]
n = 0
t1 = time.time()
Expand All @@ -575,8 +575,8 @@ def _demo(heading, source, encrypted, decrypted):
t2 = time.time()
if t2 - t1 >= 5.0:
break
print "%(count)i encryptions in %(time)0.1f seconds: %(throughput)0.1f enc/s" % {
print("%(count)i encryptions in %(time)0.1f seconds: %(throughput)0.1f enc/s" % {
'count': n,
'time': t2 - t1,
'throughput': n / (t2 - t1),
}
})
4 changes: 2 additions & 2 deletions src/gmv/cmdline_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def print_help(self, out=sys.stderr):
super(CmdLineParser, self).print_help(out)
if self.epilogue:
#print >> out, '\n%s' % textwrap.fill(self.epilogue, 100, replace_whitespace = False)
print >> out, '\n%s' % self.epilogue
print('\n%s' % self.epilogue, file=out)
out.flush()

def show_usage(self, msg=None):
Expand All @@ -97,7 +97,7 @@ def die_with_usage(self, msg=None, exit_code=2):
The process exit code. Defaults to 2.
"""
if msg != None:
print >> sys.stderr, msg
print(msg, file=sys.stderr)

self.print_help(sys.stderr)
sys.exit(exit_code)
Expand Down
22 changes: 11 additions & 11 deletions src/gmv/conf/conf_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@ def _get_value_from_command_line(self):
for arg in sys.argv:
if arg.lower() == the_s:
i = sys.argv.index(arg)
#print "i = %d, val = %s\n"%(i,sys.argv[i])
#print("i = %d, val = %s\n"%(i,sys.argv[i]))
if len(sys.argv) <= i:
# No more thing to read in the command line so quit
print "Resource: Commandline argument %s has no value\n" % (self._cli_arg)
print("Resource: Commandline argument %s has no value\n" % (self._cli_arg))
return None
else:
#print "i+1 = %d, val = %s\n"%(i+1,sys.argv[i+1])
Expand Down Expand Up @@ -243,7 +243,7 @@ def get_value_as_boolean(self):
"""
val = self.get_value()
if val.lower() not in self._boolean_states:
raise ValueError, 'Not a boolean: %s' % val
raise ValueError( 'Not a boolean: %s' % val)
return self._boolean_states[val.lower()]

class MockConf(object):
Expand Down Expand Up @@ -409,9 +409,9 @@ def _load_config(self, a_file=None):
# memorize conf file path
self._configuration_file_path = a_file

except Exception, exce:
print "Can't read the config file %s" % a_file
print "Current executing from dir = %s\n" % os.getcwd()
except Exception as exce:
print("Can't read the config file %s" % a_file)
print("Current executing from dir = %s\n" % os.getcwd())
raise exce

def get_conf_file_path(self):
Expand Down Expand Up @@ -639,7 +639,7 @@ def _replace_vars(self, a_str, location, lineno= - 1):
dummy = res.get_value()
else:
dummy = self._sections[group][self.optionxform(option)]
except KeyError, _: #IGNORE:W0612
except KeyError as _: #IGNORE:W0612
raise exceptions.SubstitutionError(lineno, location, "Property %s[%s] "\
"doesn't exist in this configuration file \n" \
% (group, option))
Expand Down Expand Up @@ -682,14 +682,14 @@ def getboolean(self, section, option, default=False, fail_if_missing=False):
"""getboolean value"""
val = self.get(section, option, default, fail_if_missing)
if val.lower() not in self._boolean_states:
raise ValueError, 'Not a boolean: %s' % val
raise ValueError('Not a boolean: %s' % val)
return self._boolean_states[val.lower()]

def get_boolean(self, section, option, default=False, fail_if_missing=False):
"""get_boolean value"""
val = self.get(section, option, default, fail_if_missing)
if val.lower() not in self._boolean_states:
raise ValueError, 'Not a boolean: %s' % val
raise ValueError('Not a boolean: %s' % val)
return self._boolean_states[val.lower()]

def get_list(self, section, option, default=None, fail_if_missing=False):
Expand All @@ -701,7 +701,7 @@ def get_list(self, section, option, default=None, fail_if_missing=False):
try:
compiler = struct_parser.Compiler()
return compiler.compile_list(val)
except struct_parser.CompilerError, err:
except struct_parser.CompilerError as err:
raise exceptions.Error(err.message)

def getlist(self, section, option, default=None, fail_if_missing=False):
Expand All @@ -722,7 +722,7 @@ def get_dict(self, section, option, default=None, fail_if_missing=False):
try:
compiler = struct_parser.Compiler()
return compiler.compile_dict(val)
except struct_parser.CompilerError, err:
except struct_parser.CompilerError as err:
raise exceptions.Error(err.message)

@classmethod
Expand Down
4 changes: 2 additions & 2 deletions src/gmv/conf/conf_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def test_dict_error(self):

try:
self.conf.get_dict('GroupTestValueStruct', 'dict_error')
except Exception, err:
except Exception as err:
self.assertEquals(err.message, "Expression \"{1:2,'v b': a\" cannot be converted as a dict.")
return

Expand All @@ -277,7 +277,7 @@ def test_list_error(self):
try:
the_list = self.conf.get_list('GroupTestValueStruct', 'list_error')
print('the_list = %s\n' % (the_list))
except Exception, err:
except Exception as err:
self.assertEquals(err.message, 'Unsupported token (type: @, value : OP) (line=1,col=3).')
return

Expand Down
15 changes: 9 additions & 6 deletions src/gmv/conf/utils/struct_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
'''
import tokenize
import token
import StringIO
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3

class TokenizerError(Exception):
"""Base class for All exceptions"""
Expand Down Expand Up @@ -109,7 +112,7 @@ def tokenize(self, a_program, a_eatable_token_types = ()):
Raises:
exception TokenizerError if the syntax of the aString string is incorrect
"""
g_info = tokenize.generate_tokens(StringIO.StringIO(a_program).readline) # tokenize the string
g_info = tokenize.generate_tokens(StringIO(a_program).readline) # tokenize the string

for toknum, tokval, tokbeg, tokend, tokline in g_info:
if token.tok_name[toknum] not in a_eatable_token_types:
Expand Down Expand Up @@ -266,7 +269,7 @@ def compile_list(self, a_to_compile_str):
try:
tokenizer = Tokenizer()
tokenizer.tokenize(a_to_compile_str, self._tokens_to_ignore)
except tokenize.TokenError, err:
except tokenize.TokenError as err:

#translate this error into something understandable.
#It is because the bloody tokenizer counts the brackets
Expand All @@ -287,7 +290,7 @@ def compile_dict(self, a_to_compile_str):
try:
tokenizer = Tokenizer()
tokenizer.tokenize(a_to_compile_str, self._tokens_to_ignore)
except tokenize.TokenError, err:
except tokenize.TokenError as err:

#translate this error into something understandable.
#It is because the bloody tokenizer counts the brackets
Expand Down Expand Up @@ -423,8 +426,8 @@ def _compile_litteral(self, a_tokenizer):
#check if the string is unicode
if len(the_token.value) >= 3 and the_token.value[:2] == "u'":
#unicode string
#dummy = unicode(the_token.value[2:-1], 'utf_8') #decode from utf-8 encoding not necessary if read full utf-8 file
dummy = unicode(the_token.value[2:-1])
#dummy = str(the_token.value[2:-1], 'utf_8') #decode from utf-8 encoding not necessary if read full utf-8 file
dummy = str(the_token.value[2:-1])
else:
#ascii string
# the value contains the quote or double quotes so remove them always
Expand Down
6 changes: 3 additions & 3 deletions src/gmv/conf/utils/struct_parser_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def test_list_error(self):

try:
compiler.compile_list(the_string)
except CompilerError, err:
except CompilerError as err:
self.assertEqual(err.message, 'Expression " a ]" cannot be converted as a list.')

def test_list_unicode_val(self):
Expand Down Expand Up @@ -126,7 +126,7 @@ def test_list_error_2(self):

try:
compiler.compile_list(the_string)
except CompilerError, err:
except CompilerError as err:
self.assertEqual(err.message, 'Unsupported token (type: @, value : OP) (line=1,col=3).')

def test_simple_dict(self):
Expand All @@ -148,7 +148,7 @@ def test_dict_error(self):

try:
compiler.compile_dict(the_string)
except CompilerError, err:
except CompilerError as err:
self.assertEqual(err.message, 'Expression "{\'a\':1, b:2 " cannot be converted as a dict.')

def test_dict_with_list(self):
Expand Down
18 changes: 9 additions & 9 deletions src/gmv/credential_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import json
import base64
import urllib #for urlencode
import urllib2
import urllib.request #for urlencode

import os
import getpass
Expand Down Expand Up @@ -74,7 +74,7 @@ def get_secret_key(cls, a_filepath):
else:
secret = gmvault_utils.make_password()

fdesc = os.open(a_filepath, os.O_CREAT|os.O_WRONLY, 0600)
fdesc = os.open(a_filepath, os.O_CREAT|os.O_WRONLY, 0o600)
try:
the_bytes = os.write(fdesc, secret)
finally:
Expand All @@ -92,7 +92,7 @@ def store_passwd(cls, email, passwd):
"""
passwd_file = '%s/%s.passwd' % (gmvault_utils.get_home_dir_path(), email)

fdesc = os.open(passwd_file, os.O_CREAT|os.O_WRONLY, 0600)
fdesc = os.open(passwd_file, os.O_CREAT|os.O_WRONLY, 0o600)

cipher = blowfish.Blowfish(cls.get_secret_key(cls.SECRET_FILEPATH % (gmvault_utils.get_home_dir_path())))
cipher.initCTR()
Expand Down Expand Up @@ -153,7 +153,7 @@ def read_oauth2_tok_sec(cls, email):
try:
with open(user_oauth_file_path) as oauth_file:
oauth_result = json.load(oauth_file)
except Exception, _: #pylint: disable-msg=W0703
except Exception as _: #pylint: disable-msg=W0703
LOG.critical("Cannot read oauth credentials from %s. Force oauth credentials renewal." % user_oauth_file_path)
LOG.critical("=== Exception traceback ===")
LOG.critical(gmvault_utils.get_exception_traceback())
Expand Down Expand Up @@ -261,8 +261,8 @@ def _get_oauth2_acc_tok_from_ref_tok(cls, refresh_token):
request_url = '%s/%s' % (account_base_url, 'o/oauth2/token')

try:
response = urllib2.urlopen(request_url, urllib.urlencode(params)).read()
except Exception, err: #pylint: disable-msg=W0703
response = urllib.request.urlopen(request_url, urllib.urlencode(params)).read()
except Exception as err: #pylint: disable-msg=W0703
LOG.critical("Error: Problems when trying to connect to Google oauth2 endpoint: %s.\n" % (request_url))
raise err

Expand Down Expand Up @@ -300,8 +300,8 @@ def _get_authorization_tokens(cls, authorization_code):
request_url = '%s/%s' % (account_base_url, 'o/oauth2/token')

try:
response = urllib2.urlopen(request_url, urllib.urlencode(params)).read()
except Exception, err: #pylint: disable-msg=W0703
response = urllib.request.urlopen(request_url, urllib.urlencode(params)).read()
except Exception as err: #pylint: disable-msg=W0703
LOG.critical("Error: Problems when trying to connect to Google oauth2 endpoint: %s." % (request_url))
raise err

Expand All @@ -325,7 +325,7 @@ def _get_oauth2_tokens(cls, email, use_webbrowser = False, debug=False):
if use_webbrowser:
try:
webbrowser.open(str(permission_url))
except Exception, err: #pylint: disable-msg=W0703
except Exception as err: #pylint: disable-msg=W0703
LOG.critical("Error: %s.\n" % (err) )
LOG.critical("=== Exception traceback ===")
LOG.critical(gmvault_utils.get_exception_traceback())
Expand Down
8 changes: 4 additions & 4 deletions src/gmv/gmv_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ def _parse_common_args(cls, options, parser, parsed_args, list_of_types = []): #
port = int(options.port)
else:
port = options.port
except Exception, _: #pylint:disable=W0703
except Exception as _: #pylint:disable=W0703
parser.error("--port option %s is not a number. Please check the port value" % (port))

# add port
Expand Down Expand Up @@ -763,7 +763,7 @@ def run(self, args): #pylint:disable=R0912

on_error = False

except KeyboardInterrupt, _:
except KeyboardInterrupt as _:
LOG.critical("\nCTRL-C. Stop all operations.\n")
on_error = False
except socket.error:
Expand All @@ -773,7 +773,7 @@ def run(self, args): #pylint:disable=R0912
LOG.critical(gmvault_utils.get_exception_traceback())
LOG.critical("=== End of Exception traceback ===\n")
die_with_usage = False
except imaplib.IMAP4.error, imap_err:
except imaplib.IMAP4.error as imap_err:
#bad login or password
if str(imap_err) in ['[AUTHENTICATIONFAILED] Invalid credentials (Failure)', \
'[ALERT] Web login required: http://support.google.com/'\
Expand All @@ -787,7 +787,7 @@ def run(self, args): #pylint:disable=R0912
LOG.critical("=== Exception traceback ===")
LOG.critical(gmvault_utils.get_exception_traceback())
LOG.critical("=== End of Exception traceback ===\n")
except Exception, err:
except Exception as err:
LOG.critical("Error: %s. \n" % (err) )
LOG.critical("=== Exception traceback ===")
LOG.critical(gmvault_utils.get_exception_traceback())
Expand Down
Loading