Merge "Fix python 3.x related Hacking warnings"

This commit is contained in:
Jenkins
2013-11-12 04:38:33 +00:00
committed by Gerrit Code Review
5 changed files with 82 additions and 72 deletions
+2 -1
View File
@@ -230,7 +230,8 @@ class HTTPClient(object):
raise exc.InvalidEndpoint(message=message) raise exc.InvalidEndpoint(message=message)
except (socket.error, socket.timeout) as e: except (socket.error, socket.timeout) as e:
endpoint = self.endpoint endpoint = self.endpoint
message = "Error communicating with %(endpoint)s %(e)s" % locals() message = ("Error communicating with %(endpoint)s %(e)s" %
{'endpoint': endpoint, 'e': e})
raise exc.CommunicationError(message=message) raise exc.CommunicationError(message=message)
body_iter = ResponseBodyIterator(resp) body_iter = ResponseBodyIterator(resp)
+5 -3
View File
@@ -13,6 +13,8 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from __future__ import print_function
import errno import errno
import os import os
import sys import sys
@@ -114,14 +116,14 @@ def print_list(objs, fields, formatters={}):
row.append(data) row.append(data)
pt.add_row(row) pt.add_row(row)
print strutils.safe_encode(pt.get_string()) print(strutils.safe_encode(pt.get_string()))
def print_dict(d): def print_dict(d):
pt = prettytable.PrettyTable(['Property', 'Value'], caching=False) pt = prettytable.PrettyTable(['Property', 'Value'], caching=False)
pt.align = 'l' pt.align = 'l'
[pt.add_row(list(r)) for r in d.iteritems()] [pt.add_row(list(r)) for r in d.iteritems()]
print strutils.safe_encode(pt.get_string(sortby='Property')) print(strutils.safe_encode(pt.get_string(sortby='Property')))
def find_resource(manager, name_or_id): def find_resource(manager, name_or_id):
@@ -197,7 +199,7 @@ def import_versioned_module(version, submodule=None):
def exit(msg=''): def exit(msg=''):
if msg: if msg:
print >> sys.stderr, strutils.safe_encode(msg) print(strutils.safe_encode(msg), file=sys.stderr)
sys.exit(1) sys.exit(1)
+4 -2
View File
@@ -17,6 +17,8 @@
Command-line interface to the OpenStack Images API. Command-line interface to the OpenStack Images API.
""" """
from __future__ import print_function
import argparse import argparse
import json import json
import logging import logging
@@ -520,8 +522,8 @@ def main():
try: try:
OpenStackImagesShell().main(map(strutils.safe_decode, sys.argv[1:])) OpenStackImagesShell().main(map(strutils.safe_decode, sys.argv[1:]))
except KeyboardInterrupt: except KeyboardInterrupt:
print >> sys.stderr, '... terminating glance client' print('... terminating glance client', file=sys.stderr)
sys.exit(1) sys.exit(1)
except Exception as e: except Exception as e:
print >> sys.stderr, utils.exception_to_str(e) print(utils.exception_to_str(e), file=sys.stderr)
sys.exit(1) sys.exit(1)
+59 -56
View File
@@ -18,6 +18,8 @@ DEPRECATED functions that implement the same command line interface as the
legacy glance client. legacy glance client.
""" """
from __future__ import print_function
import argparse import argparse
import sys import sys
import urlparse import urlparse
@@ -51,7 +53,7 @@ def get_image_filters_from_args(args):
try: try:
fields = get_image_fields_from_args(args) fields = get_image_fields_from_args(args)
except RuntimeError as e: except RuntimeError as e:
print e print(e)
return FAILURE return FAILURE
SUPPORTED_FILTERS = ['name', 'disk_format', 'container_format', 'status', SUPPORTED_FILTERS = ['name', 'disk_format', 'container_format', 'status',
@@ -78,27 +80,27 @@ def print_image_formatted(client, image):
hostbase = "%s:%s" % (uri_parts.hostname, uri_parts.port) hostbase = "%s:%s" % (uri_parts.hostname, uri_parts.port)
else: else:
hostbase = uri_parts.hostname hostbase = uri_parts.hostname
print "URI: %s://%s/v1/images/%s" % (uri_parts.scheme, hostbase, image.id) print("URI: %s://%s/v1/images/%s" % (uri_parts.scheme, hostbase, image.id))
print "Id: %s" % image.id print("Id: %s" % image.id)
print "Public: " + (image.is_public and "Yes" or "No") print("Public: " + (image.is_public and "Yes" or "No"))
print "Protected: " + (image.protected and "Yes" or "No") print("Protected: " + (image.protected and "Yes" or "No"))
print "Name: %s" % getattr(image, 'name', '') print("Name: %s" % getattr(image, 'name', ''))
print "Status: %s" % image.status print("Status: %s" % image.status)
print "Size: %d" % int(image.size) print("Size: %d" % int(image.size))
print "Disk format: %s" % getattr(image, 'disk_format', '') print("Disk format: %s" % getattr(image, 'disk_format', ''))
print "Container format: %s" % getattr(image, 'container_format', '') print("Container format: %s" % getattr(image, 'container_format', ''))
print "Minimum Ram Required (MB): %s" % image.min_ram print("Minimum Ram Required (MB): %s" % image.min_ram)
print "Minimum Disk Required (GB): %s" % image.min_disk print("Minimum Disk Required (GB): %s" % image.min_disk)
if hasattr(image, 'owner'): if hasattr(image, 'owner'):
print "Owner: %s" % image.owner print("Owner: %s" % image.owner)
if len(image.properties) > 0: if len(image.properties) > 0:
for k, v in image.properties.items(): for k, v in image.properties.items():
print "Property '%s': %s" % (k, v) print("Property '%s': %s" % (k, v))
print "Created at: %s" % image.created_at print("Created at: %s" % image.created_at)
if hasattr(image, 'deleted_at'): if hasattr(image, 'deleted_at'):
print "Deleted at: %s" % image.deleted_at print("Deleted at: %s" % image.deleted_at)
if hasattr(image, 'updated_at'): if hasattr(image, 'updated_at'):
print "Updated at: %s" % image.updated_at print("Updated at: %s" % image.updated_at)
@utils.arg('--silent-upload', action="store_true", @utils.arg('--silent-upload', action="store_true",
@@ -109,7 +111,7 @@ def do_add(gc, args):
try: try:
fields = get_image_fields_from_args(args.fields) fields = get_image_fields_from_args(args.fields)
except RuntimeError as e: except RuntimeError as e:
print e print(e)
return FAILURE return FAILURE
image_meta = { image_meta = {
@@ -131,7 +133,7 @@ def do_add(gc, args):
unsupported_fields = ['status', 'size'] unsupported_fields = ['status', 'size']
for field in unsupported_fields: for field in unsupported_fields:
if field in fields.keys(): if field in fields.keys():
print 'Found non-settable field %s. Removing.' % field print('Found non-settable field %s. Removing.' % field)
fields.pop(field) fields.pop(field)
# We need either a location or image data/stream to add... # We need either a location or image data/stream to add...
@@ -158,19 +160,19 @@ def do_add(gc, args):
if not args.dry_run: if not args.dry_run:
image = gc.images.create(**image_meta) image = gc.images.create(**image_meta)
print "Added new image with ID: %s" % image.id print("Added new image with ID: %s" % image.id)
if args.verbose: if args.verbose:
print "Returned the following metadata for the new image:" print("Returned the following metadata for the new image:")
for k, v in sorted(image.to_dict().items()): for k, v in sorted(image.to_dict().items()):
print " %(k)30s => %(v)s" % locals() print(" %(k)30s => %(v)s" % {'k': k, 'v': v})
else: else:
print "Dry run. We would have done the following:" print("Dry run. We would have done the following:")
def _dump(dict): def _dump(dict):
for k, v in sorted(dict.items()): for k, v in sorted(dict.items()):
print " %(k)30s => %(v)s" % locals() print(" %(k)30s => %(v)s" % {'k': k, 'v': v})
print "Add new image with metadata:" print("Add new image with metadata:")
_dump(image_meta) _dump(image_meta)
return SUCCESS return SUCCESS
@@ -183,7 +185,7 @@ def do_update(gc, args):
try: try:
fields = get_image_fields_from_args(args.fields) fields = get_image_fields_from_args(args.fields)
except RuntimeError as e: except RuntimeError as e:
print e print(e)
return FAILURE return FAILURE
image_meta = {} image_meta = {}
@@ -193,7 +195,7 @@ def do_update(gc, args):
'updated_at', 'size', 'status'] 'updated_at', 'size', 'status']
for field in nonmodifiable_fields: for field in nonmodifiable_fields:
if field in fields.keys(): if field in fields.keys():
print 'Found non-modifiable field %s. Removing.' % field print('Found non-modifiable field %s. Removing.' % field)
fields.pop(field) fields.pop(field)
base_image_fields = ['disk_format', 'container_format', 'name', base_image_fields = ['disk_format', 'container_format', 'name',
@@ -215,18 +217,18 @@ def do_update(gc, args):
if not args.dry_run: if not args.dry_run:
image = gc.images.update(args.id, **image_meta) image = gc.images.update(args.id, **image_meta)
print "Updated image %s" % args.id print("Updated image %s" % args.id)
if args.verbose: if args.verbose:
print "Updated image metadata for image %s:" % args.id print("Updated image metadata for image %s:" % args.id)
print_image_formatted(gc, image) print_image_formatted(gc, image)
else: else:
def _dump(dict): def _dump(dict):
for k, v in sorted(dict.items()): for k, v in sorted(dict.items()):
print " %(k)30s => %(v)s" % locals() print(" %(k)30s => %(v)s" % {'k': k, 'v': v})
print "Dry run. We would have done the following:" print("Dry run. We would have done the following:")
print "Update existing image with metadata:" print("Update existing image with metadata:")
_dump(image_meta) _dump(image_meta)
return SUCCESS return SUCCESS
@@ -237,7 +239,7 @@ def do_delete(gc, args):
"""DEPRECATED! Use image-delete instead.""" """DEPRECATED! Use image-delete instead."""
if not (args.force or if not (args.force or
user_confirm("Delete image %s?" % args.id, default=False)): user_confirm("Delete image %s?" % args.id, default=False)):
print 'Not deleting image %s' % args.id print('Not deleting image %s' % args.id)
return FAILURE return FAILURE
gc.images.get(args.id).delete() gc.images.get(args.id).delete()
@@ -289,14 +291,14 @@ def do_index(gc, args):
pretty_table.add_column(20, label="Container Format") pretty_table.add_column(20, label="Container Format")
pretty_table.add_column(14, label="Size", just="r") pretty_table.add_column(14, label="Size", just="r")
print pretty_table.make_header() print(pretty_table.make_header())
for image in images: for image in images:
print pretty_table.make_row(image.id, print(pretty_table.make_row(image.id,
image.name, image.name,
image.disk_format, image.disk_format,
image.container_format, image.container_format,
image.size) image.size))
@utils.arg('--limit', dest="limit", metavar="LIMIT", default=10, @utils.arg('--limit', dest="limit", metavar="LIMIT", default=10,
@@ -313,29 +315,30 @@ def do_details(gc, args):
images = _get_images(gc, args) images = _get_images(gc, args)
for i, image in enumerate(images): for i, image in enumerate(images):
if i == 0: if i == 0:
print "=" * 80 print("=" * 80)
print_image_formatted(gc, image) print_image_formatted(gc, image)
print "=" * 80 print("=" * 80)
def do_clear(gc, args): def do_clear(gc, args):
"""DEPRECATED!""" """DEPRECATED!"""
if not (args.force or if not (args.force or
user_confirm("Delete all images?", default=False)): user_confirm("Delete all images?", default=False)):
print 'Not deleting any images' print('Not deleting any images')
return FAILURE return FAILURE
images = gc.images.list() images = gc.images.list()
for image in images: for image in images:
if args.verbose: if args.verbose:
print 'Deleting image %s "%s" ...' % (image.id, image.name), print('Deleting image %s "%s" ...' % (image.id, image.name),
end=' ')
try: try:
image.delete() image.delete()
if args.verbose: if args.verbose:
print 'done' print('done')
except Exception as e: except Exception as e:
print 'Failed to delete image %s' % image.id print('Failed to delete image %s' % image.id)
print e print(e)
return FAILURE return FAILURE
return SUCCESS return SUCCESS
@@ -351,11 +354,11 @@ def do_image_members(gc, args):
if memb.can_share: if memb.can_share:
can_share = ' *' can_share = ' *'
sharers += 1 sharers += 1
print "%s%s" % (memb.member_id, can_share) print("%s%s" % (memb.member_id, can_share))
# Emit a footnote # Emit a footnote
if sharers > 0: if sharers > 0:
print "\n(*: Can share image)" print("\n(*: Can share image)")
@utils.arg('--can-share', default=False, action="store_true", @utils.arg('--can-share', default=False, action="store_true",
@@ -367,7 +370,7 @@ def do_member_images(gc, args):
members = gc.image_members.list(member=args.member_id) members = gc.image_members.list(member=args.member_id)
if not len(members): if not len(members):
print "No images shared with member %s" % args.member_id print("No images shared with member %s" % args.member_id)
return SUCCESS return SUCCESS
sharers = 0 sharers = 0
@@ -377,11 +380,11 @@ def do_member_images(gc, args):
if memb.can_share: if memb.can_share:
can_share = ' *' can_share = ' *'
sharers += 1 sharers += 1
print "%s%s" % (memb.image_id, can_share) print("%s%s" % (memb.image_id, can_share))
# Emit a footnote # Emit a footnote
if sharers > 0: if sharers > 0:
print "\n(*: Can share image)" print("\n(*: Can share image)")
@utils.arg('--can-share', default=False, action="store_true", @utils.arg('--can-share', default=False, action="store_true",
@@ -396,11 +399,11 @@ def do_members_replace(gc, args):
gc.image_members.delete(args.image_id, member.member_id) gc.image_members.delete(args.image_id, member.member_id)
gc.image_members.create(args.image_id, args.member_id, args.can_share) gc.image_members.create(args.image_id, args.member_id, args.can_share)
else: else:
print "Dry run. We would have done the following:" print("Dry run. We would have done the following:")
print ('Replace members of image %s with "%s"' print('Replace members of image %s with "%s"'
% (args.image_id, args.member_id)) % (args.image_id, args.member_id))
if args.can_share: if args.can_share:
print "New member would have been able to further share image." print("New member would have been able to further share image.")
@utils.arg('--can-share', default=False, action="store_true", @utils.arg('--can-share', default=False, action="store_true",
@@ -413,11 +416,11 @@ def do_member_add(gc, args):
if not args.dry_run: if not args.dry_run:
gc.image_members.create(args.image_id, args.member_id, args.can_share) gc.image_members.create(args.image_id, args.member_id, args.can_share)
else: else:
print "Dry run. We would have done the following:" print("Dry run. We would have done the following:")
print ('Add "%s" to membership of image %s' % print('Add "%s" to membership of image %s' %
(args.member_id, args.image_id)) (args.member_id, args.image_id))
if args.can_share: if args.can_share:
print "New member would have been able to further share image." print("New member would have been able to further share image.")
def user_confirm(prompt, default=False): def user_confirm(prompt, default=False):
+12 -10
View File
@@ -13,6 +13,8 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from __future__ import print_function
import argparse import argparse
import copy import copy
import sys import sys
@@ -315,18 +317,18 @@ def do_image_delete(gc, args):
image = utils.find_resource(gc.images, args_image) image = utils.find_resource(gc.images, args_image)
try: try:
if args.verbose: if args.verbose:
print 'Requesting image delete for %s ...' % \ print('Requesting image delete for %s ...' %
strutils.safe_encode(args_image), strutils.safe_encode(args_image), end=' ')
gc.images.delete(image) gc.images.delete(image)
if args.verbose: if args.verbose:
print '[Done]' print('[Done]')
except exc.HTTPException as e: except exc.HTTPException as e:
if args.verbose: if args.verbose:
print '[Fail]' print('[Fail]')
print '%s: Unable to delete image %s' % (e, args_image) print('%s: Unable to delete image %s' % (e, args_image))
@utils.arg('--image-id', metavar='<IMAGE_ID>', @utils.arg('--image-id', metavar='<IMAGE_ID>',
@@ -336,14 +338,14 @@ def do_image_delete(gc, args):
def do_member_list(gc, args): def do_member_list(gc, args):
"""Describe sharing permissions by image or tenant.""" """Describe sharing permissions by image or tenant."""
if args.image_id and args.tenant_id: if args.image_id and args.tenant_id:
print 'Unable to filter members by both --image-id and --tenant-id.' print('Unable to filter members by both --image-id and --tenant-id.')
sys.exit(1) sys.exit(1)
elif args.image_id: elif args.image_id:
kwargs = {'image': args.image_id} kwargs = {'image': args.image_id}
elif args.tenant_id: elif args.tenant_id:
kwargs = {'member': args.tenant_id} kwargs = {'member': args.tenant_id}
else: else:
print 'Unable to list all members. Specify --image-id or --tenant-id' print('Unable to list all members. Specify --image-id or --tenant-id')
sys.exit(1) sys.exit(1)
members = gc.image_members.list(**kwargs) members = gc.image_members.list(**kwargs)
@@ -373,6 +375,6 @@ def do_member_delete(gc, args):
if not args.dry_run: if not args.dry_run:
gc.image_members.delete(image_id, args.tenant_id) gc.image_members.delete(image_id, args.tenant_id)
else: else:
print "Dry run. We would have done the following:" print("Dry run. We would have done the following:")
print ('Remove "%s" from the member list of image ' print('Remove "%s" from the member list of image '
'"%s"' % (args.tenant_id, args.image)) '"%s"' % (args.tenant_id, args.image))