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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -41,8 +41,7 @@ commands = bash tools/lintstack.sh
[flake8]
# TODO: These are not intentionally disabled, reenable when fixed:
# H233: Python 3.x incompatible print operator
# 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 = _
exclude = .venv,.tox,dist,doc,openstack,*egg