Replace python print operator with print function (pep H233, py33)

'print' function is compatible with 2.x and 3.x python versions

Partially-implements blueprint py3-compatibility

Change-Id: Idea6704be7f49778ca9e99be5b7f449cb89f39dc
This commit is contained in:
Valeriy Ponomaryov 2014-07-02 06:12:42 -04:00
parent b1b8a62882
commit 4c9a4808b7
9 changed files with 81 additions and 73 deletions

View File

@ -54,6 +54,8 @@
CLI interface for manila management. CLI interface for manila management.
""" """
from __future__ import print_function
import os import os
import sys import sys
import uuid import uuid
@ -176,10 +178,10 @@ class ShellCommands(object):
def _db_error(caught_exception): def _db_error(caught_exception):
print caught_exception print(caught_exception)
print _("The above error may show that the database has not " print(_("The above error may show that the database has not "
"been created.\nPlease create a database using " "been created.\nPlease create a database using "
"'manila-manage db sync' before running this command.") "'manila-manage db sync' before running this command."))
exit(1) exit(1)
@ -191,8 +193,7 @@ class HostCommands(object):
def list(self, zone=None): def list(self, zone=None):
"""Show a list of all physical hosts. Filter by zone. """Show a list of all physical hosts. Filter by zone.
args: [zone]""" args: [zone]"""
print "%-25s\t%-15s" % (_('host'), print("%-25s\t%-15s" % (_('host'), _('zone')))
_('zone'))
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
services = db.service_get_all(ctxt) services = db.service_get_all(ctxt)
if zone: if zone:
@ -203,7 +204,7 @@ class HostCommands(object):
hosts.append(srv) hosts.append(srv)
for h in hosts: for h in hosts:
print "%-25s\t%-15s" % (h['host'], h['availability_zone']) print("%-25s\t%-15s" % (h['host'], h['availability_zone']))
class DbCommands(object): class DbCommands(object):
@ -220,7 +221,7 @@ class DbCommands(object):
def version(self): def version(self):
"""Print the current database version.""" """Print the current database version."""
print migration.db_version() print(migration.db_version())
class VersionCommands(object): class VersionCommands(object):
@ -245,7 +246,7 @@ class ConfigCommands(object):
def list(self): def list(self):
for key, value in CONF.iteritems(): for key, value in CONF.iteritems():
if value is not None: if value is not None:
print '%s = %s' % (key, value) print('%s = %s' % (key, value))
class GetLogCommands(object): class GetLogCommands(object):
@ -265,11 +266,11 @@ class GetLogCommands(object):
if line.find(" ERROR ") > 0: if line.find(" ERROR ") > 0:
error_found += 1 error_found += 1
if print_name == 0: if print_name == 0:
print log_file + ":-" print(log_file + ":-")
print_name = 1 print_name = 1
print "Line %d : %s" % (len(lines) - index, line) print("Line %d : %s" % (len(lines) - index, line))
if error_found == 0: if error_found == 0:
print "No errors in logfiles!" print("No errors in logfiles!")
@args('num_entries', nargs='?', type=int, default=10, @args('num_entries', nargs='?', type=int, default=10,
help='Number of entries to list (default: %(default)d)') help='Number of entries to list (default: %(default)d)')
@ -283,20 +284,20 @@ class GetLogCommands(object):
elif os.path.exists('/var/log/messages'): elif os.path.exists('/var/log/messages'):
log_file = '/var/log/messages' log_file = '/var/log/messages'
else: else:
print "Unable to find system log file!" print("Unable to find system log file!")
sys.exit(1) sys.exit(1)
lines = [line.strip() for line in open(log_file, "r")] lines = [line.strip() for line in open(log_file, "r")]
lines.reverse() lines.reverse()
print "Last %s manila syslog entries:-" % (entries) print("Last %s manila syslog entries:-" % (entries))
for line in lines: for line in lines:
if line.find("manila") > 0: if line.find("manila") > 0:
count += 1 count += 1
print "%s" % (line) print("%s" % (line))
if count == entries: if count == entries:
break break
if count == 0: if count == 0:
print "No manila entries in syslog!" print("No manila entries in syslog!")
class ServiceCommands(object): class ServiceCommands(object):
@ -306,22 +307,23 @@ class ServiceCommands(object):
ctxt = context.get_admin_context() ctxt = context.get_admin_context()
services = db.service_get_all(ctxt) services = db.service_get_all(ctxt)
print_format = "%-16s %-36s %-16s %-10s %-5s %-10s" print_format = "%-16s %-36s %-16s %-10s %-5s %-10s"
print print_format % ( print(print_format % (
_('Binary'), _('Binary'),
_('Host'), _('Host'),
_('Zone'), _('Zone'),
_('Status'), _('Status'),
_('State'), _('State'),
_('Updated At')) _('Updated At'))
)
for svc in services: for svc in services:
alive = utils.service_is_up(svc) alive = utils.service_is_up(svc)
art = ":-)" if alive else "XXX" art = ":-)" if alive else "XXX"
status = 'enabled' status = 'enabled'
if svc['disabled']: if svc['disabled']:
status = 'disabled' status = 'disabled'
print print_format % (svc['binary'], svc['host'].partition('.')[0], print(print_format % (svc['binary'], svc['host'].partition('.')[0],
svc['availability_zone'], status, art, svc['availability_zone'], status, art,
svc['updated_at']) svc['updated_at']))
CATEGORIES = { CATEGORIES = {
@ -403,10 +405,10 @@ def main():
if len(sys.argv) < 2: if len(sys.argv) < 2:
print(_("\nOpenStack manila version: %(version)s\n") % print(_("\nOpenStack manila version: %(version)s\n") %
{'version': version.version_string()}) {'version': version.version_string()})
print script_name + " category action [<args>]" print(script_name + " category action [<args>]")
print _("Available categories:") print(_("Available categories:"))
for category in CATEGORIES: for category in CATEGORIES:
print "\t%s" % category print("\t%s" % category)
sys.exit(2) sys.exit(2)
try: try:
@ -417,13 +419,13 @@ def main():
cfgfile = CONF.config_file[-1] if CONF.config_file else None cfgfile = CONF.config_file[-1] if CONF.config_file else None
if cfgfile and not os.access(cfgfile, os.R_OK): if cfgfile and not os.access(cfgfile, os.R_OK):
st = os.stat(cfgfile) st = os.stat(cfgfile)
print _("Could not read %s. Re-running with sudo") % cfgfile print(_("Could not read %s. Re-running with sudo") % cfgfile)
try: try:
os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv) os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv)
except Exception: except Exception:
print _('sudo failed, continuing as if nothing happened') print(_('sudo failed, continuing as if nothing happened'))
print _('Please re-run manila-manage as root.') print(_('Please re-run manila-manage as root.'))
sys.exit(2) sys.exit(2)
fn = CONF.category.action_fn fn = CONF.category.action_fn

View File

@ -33,6 +33,8 @@
they are needed, to avoid allowing more than is necessary. they are needed, to avoid allowing more than is necessary.
""" """
from __future__ import print_function
import ConfigParser import ConfigParser
import logging import logging
import os import os
@ -55,7 +57,7 @@ def _subprocess_setup():
def _exit_error(execname, message, errorcode, log=True): def _exit_error(execname, message, errorcode, log=True):
print "%s: %s" % (execname, message) print("%s: %s" % (execname, message))
if log: if log:
logging.error(message) logging.error(message)
sys.exit(errorcode) sys.exit(errorcode)

View File

@ -281,7 +281,6 @@ class ShareApiTest(test.TestCase):
def test_share_show(self): def test_share_show(self):
req = fakes.HTTPRequest.blank('/shares/1') req = fakes.HTTPRequest.blank('/shares/1')
res_dict = self.controller.show(req, '1') res_dict = self.controller.show(req, '1')
print res_dict
expected = { expected = {
'share': {'name': 'displayname', 'share': {'name': 'displayname',
'availability_zone': 'fakeaz', 'availability_zone': 'fakeaz',

View File

@ -30,8 +30,6 @@ class IsolationTestCase(test.TestCase):
""" """
def test_service_isolation(self): def test_service_isolation(self):
import os
print os.path.abspath(".")
self.start_service('share') self.start_service('share')
def test_rpc_consumer_isolation(self): def test_rpc_consumer_isolation(self):

View File

@ -19,6 +19,8 @@
"""Utility methods for working with WSGI servers.""" """Utility methods for working with WSGI servers."""
from __future__ import print_function
import errno import errno
import os import os
import socket import socket
@ -393,16 +395,16 @@ class Debug(Middleware):
@webob.dec.wsgify(RequestClass=Request) @webob.dec.wsgify(RequestClass=Request)
def __call__(self, req): def __call__(self, req):
print ('*' * 40) + ' REQUEST ENVIRON' print(('*' * 40) + ' REQUEST ENVIRON')
for key, value in req.environ.items(): for key, value in req.environ.items():
print key, '=', value print(key, '=', value)
print print()
resp = req.get_response(self.application) resp = req.get_response(self.application)
print ('*' * 40) + ' RESPONSE HEADERS' print(('*' * 40) + ' RESPONSE HEADERS')
for (key, value) in resp.headers.iteritems(): for (key, value) in resp.headers.iteritems():
print key, '=', value print(key, '=', value)
print print()
resp.app_iter = self.print_generator(resp.app_iter) resp.app_iter = self.print_generator(resp.app_iter)
@ -411,12 +413,12 @@ class Debug(Middleware):
@staticmethod @staticmethod
def print_generator(app_iter): def print_generator(app_iter):
"""Iterator that prints the contents of a wrapper string.""" """Iterator that prints the contents of a wrapper string."""
print ('*' * 40) + ' BODY' print(('*' * 40) + ' BODY')
for part in app_iter: for part in app_iter:
sys.stdout.write(part) sys.stdout.write(part)
sys.stdout.flush() sys.stdout.flush()
yield part yield part
print print()
class Router(object): class Router(object):

View File

@ -21,6 +21,8 @@
"""Installation script for Manila's development virtualenv.""" """Installation script for Manila's development virtualenv."""
from __future__ import print_function
import optparse import optparse
import os import os
import subprocess import subprocess
@ -48,7 +50,7 @@ def print_help():
Also, make test will automatically use the virtualenv. Also, make test will automatically use the virtualenv.
""" """
print help print(help)
def main(argv): def main(argv):

View File

@ -21,6 +21,8 @@ virtual environments.
Synced in from openstack-common Synced in from openstack-common
""" """
from __future__ import print_function
import argparse import argparse
import os import os
import subprocess import subprocess
@ -39,7 +41,7 @@ class InstallVenv(object):
self.project = project self.project = project
def die(self, message, *args): def die(self, message, *args):
print >> sys.stderr, message % args print(message % args, file=sys.stderr)
sys.exit(1) sys.exit(1)
def check_python_version(self): def check_python_version(self):
@ -86,20 +88,20 @@ class InstallVenv(object):
virtual environment. virtual environment.
""" """
if not os.path.isdir(self.venv): if not os.path.isdir(self.venv):
print 'Creating venv...', print('Creating venv...', end=' ')
if no_site_packages: if no_site_packages:
self.run_command(['virtualenv', '-q', '--no-site-packages', self.run_command(['virtualenv', '-q', '--no-site-packages',
self.venv]) self.venv])
else: else:
self.run_command(['virtualenv', '-q', self.venv]) self.run_command(['virtualenv', '-q', self.venv])
print 'done.' print('done.')
print 'Installing pip in venv...', print('Installing pip in venv...', end=' ')
if not self.run_command(['tools/with_venv.sh', 'easy_install', if not self.run_command(['tools/with_venv.sh', 'easy_install',
'pip>1.0']).strip(): 'pip>1.0']).strip():
self.die("Failed to install pip.") self.die("Failed to install pip.")
print 'done.' print('done.')
else: else:
print "venv already exists..." print("venv already exists...")
pass pass
def pip_install(self, *args): def pip_install(self, *args):
@ -108,7 +110,7 @@ class InstallVenv(object):
redirect_output=False) redirect_output=False)
def install_dependencies(self): def install_dependencies(self):
print 'Installing dependencies with pip (this can take a while)...' print('Installing dependencies with pip (this can take a while)...')
self.pip_install('pip>=1.3') self.pip_install('pip>=1.3')
self.pip_install('setuptools') self.pip_install('setuptools')
self.pip_install('-r', self.pip_requires, '-r', self.test_requires) self.pip_install('-r', self.pip_requires, '-r', self.test_requires)
@ -134,12 +136,12 @@ class Distro(InstallVenv):
return return
if self.check_cmd('easy_install'): if self.check_cmd('easy_install'):
print 'Installing virtualenv via easy_install...', print('Installing virtualenv via easy_install...', end=' ')
if self.run_command(['easy_install', 'virtualenv']): if self.run_command(['easy_install', 'virtualenv']):
print 'Succeeded' print('Succeeded')
return return
else: else:
print 'Failed' print('Failed')
self.die('ERROR: virtualenv not found.\n\n%s development' self.die('ERROR: virtualenv not found.\n\n%s development'
' requires virtualenv, please install it using your' ' requires virtualenv, please install it using your'
@ -157,7 +159,7 @@ class Fedora(Distro):
check_exit_code=False)[1] == 0 check_exit_code=False)[1] == 0
def yum_install(self, pkg, **kwargs): def yum_install(self, pkg, **kwargs):
print "Attempting to install '%s' via yum" % pkg print("Attempting to install '%s' via yum" % pkg)
self.run_command(['sudo', 'yum', 'install', '-y', pkg], **kwargs) self.run_command(['sudo', 'yum', 'install', '-y', pkg], **kwargs)
def install_virtualenv(self): def install_virtualenv(self):

View File

@ -18,6 +18,8 @@
"""pylint error checking.""" """pylint error checking."""
from __future__ import print_function
import cStringIO as StringIO import cStringIO as StringIO
import json import json
import re import re
@ -112,9 +114,9 @@ class ErrorKeys(object):
@classmethod @classmethod
def print_json(cls, errors, output=sys.stdout): def print_json(cls, errors, output=sys.stdout):
print >>output, "# automatically generated by tools/lintstack.py" print("# automatically generated by tools/lintstack.py", file=output)
for i in sorted(errors.keys()): for i in sorted(errors.keys()):
print >>output, json.dumps(i) print(json.dumps(i), file=output)
@classmethod @classmethod
def from_file(cls, filename): def from_file(cls, filename):
@ -137,7 +139,7 @@ def run_pylint():
def generate_error_keys(msg=None): def generate_error_keys(msg=None):
print "Generating", KNOWN_PYLINT_EXCEPTIONS_FILE print("Generating", KNOWN_PYLINT_EXCEPTIONS_FILE)
if msg is None: if msg is None:
msg = run_pylint() msg = run_pylint()
errors = LintOutput.from_msg_to_dict(msg) errors = LintOutput.from_msg_to_dict(msg)
@ -146,41 +148,41 @@ def generate_error_keys(msg=None):
def validate(newmsg=None): def validate(newmsg=None):
print "Loading", KNOWN_PYLINT_EXCEPTIONS_FILE print("Loading", KNOWN_PYLINT_EXCEPTIONS_FILE)
known = ErrorKeys.from_file(KNOWN_PYLINT_EXCEPTIONS_FILE) known = ErrorKeys.from_file(KNOWN_PYLINT_EXCEPTIONS_FILE)
if newmsg is None: if newmsg is None:
print "Running pylint. Be patient..." print("Running pylint. Be patient...")
newmsg = run_pylint() newmsg = run_pylint()
errors = LintOutput.from_msg_to_dict(newmsg) errors = LintOutput.from_msg_to_dict(newmsg)
print "Unique errors reported by pylint: was %d, now %d." \ print("Unique errors reported by pylint: was %d, now %d."
% (len(known), len(errors)) % (len(known), len(errors)))
passed = True passed = True
for err_key, err_list in errors.items(): for err_key, err_list in errors.items():
for err in err_list: for err in err_list:
if err_key not in known: if err_key not in known:
print err.lintoutput print(err.lintoutput)
print print()
passed = False passed = False
if passed: if passed:
print "Congrats! pylint check passed." print("Congrats! pylint check passed.")
redundant = known - set(errors.keys()) redundant = known - set(errors.keys())
if redundant: if redundant:
print "Extra credit: some known pylint exceptions disappeared." print("Extra credit: some known pylint exceptions disappeared.")
for i in sorted(redundant): for i in sorted(redundant):
print json.dumps(i) print(json.dumps(i))
print "Consider regenerating the exception file if you will." print("Consider regenerating the exception file if you will.")
else: else:
print ("Please fix the errors above. If you believe they are false " print("Please fix the errors above. If you believe they are false "
"positives, run 'tools/lintstack.py generate' to overwrite.") "positives, run 'tools/lintstack.py generate' to overwrite.")
sys.exit(1) sys.exit(1)
def usage(): def usage():
print """Usage: tools/lintstack.py [generate|validate] print("""Usage: tools/lintstack.py [generate|validate]
To generate pylint_exceptions file: tools/lintstack.py generate To generate pylint_exceptions file: tools/lintstack.py generate
To validate the current commit: tools/lintstack.py To validate the current commit: tools/lintstack.py
""" """)
def main(): def main():

View File

@ -41,8 +41,7 @@ commands = bash tools/lintstack.sh
[flake8] [flake8]
# TODO: These are not intentionally disabled, reenable when fixed: # TODO: These are not intentionally disabled, reenable when fixed:
# H233: Python 3.x incompatible print operator
# H501: Do not use locals() for string formatting # H501: Do not use locals() for string formatting
ignore = E12,E711,E712,H233,H302,H303,H304,H401,H402,H403,H404,H501,F ignore = E12,E711,E712,H302,H303,H304,H401,H402,H403,H404,H501,F
builtins = _ builtins = _
exclude = .venv,.tox,dist,doc,openstack,*egg exclude = .venv,.tox,dist,doc,openstack,*egg