diff --git a/awscli/customizations/argrename.py b/awscli/customizations/argrename.py index ac87215c2f00..b188436eac1d 100644 --- a/awscli/customizations/argrename.py +++ b/awscli/customizations/argrename.py @@ -125,13 +125,13 @@ def register_arg_renames(cli): for original, new_name in ARGUMENT_RENAMES.items(): event_portion, original_arg_name = original.rsplit('.', 1) cli.register( - 'building-argument-table.%s' % event_portion, + f'building-argument-table.{event_portion}', rename_arg(original_arg_name, new_name), ) for original, new_name in HIDDEN_ALIASES.items(): event_portion, original_arg_name = original.rsplit('.', 1) cli.register( - 'building-argument-table.%s' % event_portion, + f'building-argument-table.{event_portion}', hidden_alias(original_arg_name, new_name), ) diff --git a/awscli/customizations/arguments.py b/awscli/customizations/arguments.py index de19031122d4..a6b30eca6cb9 100644 --- a/awscli/customizations/arguments.py +++ b/awscli/customizations/arguments.py @@ -26,7 +26,7 @@ def resolve_given_outfile_path(path): return outfile = os.path.expanduser(os.path.expandvars(path)) if not os.access(os.path.dirname(os.path.abspath(outfile)), os.W_OK): - raise ParamValidationError('Unable to write to file: %s' % outfile) + raise ParamValidationError(f'Unable to write to file: {outfile}') return outfile @@ -60,7 +60,7 @@ class OverrideRequiredArgsArgument(CustomArgument): def __init__(self, session): self._session = session self._register_argument_action() - super(OverrideRequiredArgsArgument, self).__init__(**self.ARG_DATA) + super().__init__(**self.ARG_DATA) def _register_argument_action(self): self._session.register( @@ -81,11 +81,11 @@ class StatefulArgument(CustomArgument): """An argument that maintains a stateful value""" def __init__(self, *args, **kwargs): - super(StatefulArgument, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._value = None def add_to_params(self, parameters, value): - super(StatefulArgument, self).add_to_params(parameters, value) + super().add_to_params(parameters, value) self._value = value @property @@ -106,10 +106,10 @@ def __init__( # Generate default help_text if text was not provided. if 'help_text' not in kwargs: kwargs['help_text'] = ( - 'Saves the command output contents of %s ' - 'to the given filename' % self.query + f'Saves the command output contents of {self.query} ' + 'to the given filename' ) - super(QueryOutFileArgument, self).__init__(name, *args, **kwargs) + super().__init__(name, *args, **kwargs) @property def query(self): @@ -121,7 +121,7 @@ def perm(self): def add_to_params(self, parameters, value): value = resolve_given_outfile_path(value) - super(QueryOutFileArgument, self).add_to_params(parameters, value) + super().add_to_params(parameters, value) if self.value is not None: # Only register the event to save the argument if it is set self._session.register(self._after_call_event, self.save_query) @@ -203,7 +203,7 @@ def _update_arg(self, argument_table, source_arg, new_arg): class _NestedBlobArgumentParamOverwrite(CustomArgument): def __init__(self, new_arg, source_arg, source_arg_blob_member, **kwargs): - super(_NestedBlobArgumentParamOverwrite, self).__init__( + super().__init__( new_arg, **kwargs ) self._param_to_overwrite = _reverse_xform_name(source_arg) diff --git a/awscli/customizations/awslambda.py b/awscli/customizations/awslambda.py index f703555618aa..b19e6c781ad8 100644 --- a/awscli/customizations/awslambda.py +++ b/awscli/customizations/awslambda.py @@ -120,7 +120,7 @@ class ZipFileArgument(CustomArgument): def __init__(self, *args, **kwargs): self._param_to_replace = kwargs.pop('serialized_name') - super(ZipFileArgument, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def add_to_params(self, parameters, value): if value is None: @@ -144,8 +144,8 @@ class ReplacedZipFileArgument(CLIArgument): """ def __init__(self, *args, **kwargs): - super(ReplacedZipFileArgument, self).__init__(*args, **kwargs) - self._cli_name = '--%s' % kwargs['name'] + super().__init__(*args, **kwargs) + self._cli_name = '--{}'.format(kwargs['name']) self._param_to_replace = kwargs['serialized_name'] def add_to_params(self, parameters, value): @@ -155,9 +155,9 @@ def add_to_params(self, parameters, value): if 'ZipFile' in unpacked: raise ParamValidationError( "ZipFile cannot be provided " - "as part of the %s argument. " + f"as part of the {self._cli_name} argument. " "Please use the '--zip-file' " - "option instead to specify a zip file." % self._cli_name + "option instead to specify a zip file." ) if parameters.get(self._param_to_replace): parameters[self._param_to_replace].update(unpacked) diff --git a/awscli/customizations/binaryformat.py b/awscli/customizations/binaryformat.py index 7ac8030231c7..3d031a29e905 100644 --- a/awscli/customizations/binaryformat.py +++ b/awscli/customizations/binaryformat.py @@ -57,7 +57,7 @@ def _visit_scalar(self, parent, shape, name, value): try: parent[name] = base64.b64decode(value) except (binascii.Error, TypeError): - raise InvalidBase64Error('Invalid base64: "%s"' % value) + raise InvalidBase64Error(f'Invalid base64: "{value}"') class BinaryFormatHandler: diff --git a/awscli/customizations/cliinput.py b/awscli/customizations/cliinput.py index d145e967eac2..e1196502ea68 100644 --- a/awscli/customizations/cliinput.py +++ b/awscli/customizations/cliinput.py @@ -54,7 +54,7 @@ def _register_argument_action(self): self._session.register( 'calling-command.*', self.add_to_call_parameters ) - super(CliInputArgument, self)._register_argument_action() + super()._register_argument_action() def add_to_call_parameters(self, call_parameters, parsed_args, **kwargs): arg_value = self._get_arg_value(parsed_args) @@ -66,7 +66,7 @@ def add_to_call_parameters(self, call_parameters, parsed_args, **kwargs): raise ParamError( self.cli_name, "Invalid type: expecting map, " - "received %s" % type(loaded_params), + f"received {type(loaded_params)}", ) self._update_call_parameters(call_parameters, loaded_params) diff --git a/awscli/customizations/cloudfront.py b/awscli/customizations/cloudfront.py index cd9ca8f3bd1f..0b0b78cd5fcb 100644 --- a/awscli/customizations/cloudfront.py +++ b/awscli/customizations/cloudfront.py @@ -78,7 +78,7 @@ def register(event_handler): def unique_string(prefix='cli'): - return '%s-%s-%s' % (prefix, int(time.time()), random.randint(1, 1000000)) + return f'{prefix}-{int(time.time())}-{random.randint(1, 1000000)}' def _add_paths(argument_table, **kwargs): @@ -92,7 +92,7 @@ def __init__(self): 'The space-separated paths to be invalidated.' ' Note: --invalidation-batch and --paths are mutually exclusive.' ) - super(PathsArgument, self).__init__('paths', nargs='+', help_text=doc) + super().__init__('paths', nargs='+', help_text=doc) def add_to_params(self, parameters, value): if value is not None: @@ -113,7 +113,7 @@ def __init__( help_text='', ): argument_table[exclusive_to].required = False - super(ExclusiveArgument, self).__init__( + super().__init__( name, help_text=self.DOC % (help_text, exclusive_to) ) @@ -138,7 +138,7 @@ def distribution_config_template(self): class OriginDomainName(ExclusiveArgument): def __init__(self, argument_table): - super(OriginDomainName, self).__init__( + super().__init__( 'origin-domain-name', argument_table, help_text='The domain name for your origin.', @@ -174,7 +174,7 @@ def add_to_params(self, parameters, value): class CreateDefaultRootObject(ExclusiveArgument): def __init__(self, argument_table, help_text=''): - super(CreateDefaultRootObject, self).__init__( + super().__init__( 'default-root-object', argument_table, help_text=help_text @@ -194,7 +194,7 @@ def add_to_params(self, parameters, value): class UpdateDefaultRootObject(CreateDefaultRootObject): def __init__(self, context, argument_table): - super(UpdateDefaultRootObject, self).__init__( + super().__init__( argument_table, help_text=( 'The object that you want CloudFront to return (for example, ' diff --git a/awscli/customizations/codecommit.py b/awscli/customizations/codecommit.py index 0c79d51b26f2..8ddd4d404c15 100644 --- a/awscli/customizations/codecommit.py +++ b/awscli/customizations/codecommit.py @@ -98,7 +98,7 @@ class CodeCommitGetCommand(BasicCommand): ] def __init__(self, session): - super(CodeCommitGetCommand, self).__init__(session) + super().__init__(session) def _run_main(self, args, parsed_globals): git_parameters = self.read_git_parameters() @@ -138,7 +138,7 @@ def read_git_parameters(self): return parsed def extract_url(self, parameters): - url = '{0}://{1}/{2}'.format( + url = '{}://{}/{}'.format( parameters['protocol'], parameters['host'], parameters['path'] ) return url @@ -173,7 +173,7 @@ def sign_request(self, region, url_to_sign): logger.debug('StringToSign:\n%s', string_to_sign) signature = signer.signature(string_to_sign, request) logger.debug('Signature:\n%s', signature) - return '{0}Z{1}'.format(request.context['timestamp'], signature) + return '{}Z{}'.format(request.context['timestamp'], signature) class CodeCommitCommand(BasicCommand): diff --git a/awscli/customizations/commands.py b/awscli/customizations/commands.py index c2c5f915e295..86a17004c0ff 100644 --- a/awscli/customizations/commands.py +++ b/awscli/customizations/commands.py @@ -138,9 +138,9 @@ def __call__(self, args, parsed_globals): # an arg parser and parse them. self._subcommand_table = self._build_subcommand_table() self._arg_table = self._build_arg_table() - event = 'before-building-argument-table-parser.%s' % ".".join( + event = 'before-building-argument-table-parser.{}'.format(".".join( self.lineage_names - ) + )) self._session.emit( event, argument_table=self._arg_table, @@ -177,7 +177,7 @@ def __call__(self, args, parsed_globals): # a chance to process and override its value. if self._should_allow_plugins_override(cli_argument, value): override = self._session.emit_first_non_none_response( - 'process-cli-arg.%s.%s' % ('custom', self.name), + 'process-cli-arg.{}.{}'.format('custom', self.name), cli_argument=cli_argument, value=value, operation=None, @@ -204,7 +204,7 @@ def __call__(self, args, parsed_globals): # function for this top level command. if remaining: raise ParamValidationError( - "Unknown options: %s" % ','.join(remaining) + "Unknown options: {}".format(','.join(remaining)) ) rc = self._run_main(parsed_args, parsed_globals) if rc is None: @@ -239,7 +239,7 @@ def _build_subcommand_table(self): subcommand_table[subcommand_name] = subcommand_class(self._session) name = '_'.join([c.name for c in self.lineage]) self._session.emit( - 'building-command-table.%s' % name, + f'building-command-table.{name}', command_table=subcommand_table, session=self._session, command_object=self, @@ -277,7 +277,7 @@ def _build_arg_table(self): arg_table = OrderedDict() name = '_'.join([c.name for c in self.lineage]) self._session.emit( - 'building-arg-table.%s' % name, arg_table=self.ARG_TABLE + f'building-arg-table.{name}', arg_table=self.ARG_TABLE ) for arg_data in self.ARG_TABLE: # If a custom schema was passed in, create the argument_model @@ -328,9 +328,9 @@ def lineage(self, value): def _raise_usage_error(self): lineage = ' '.join([c.name for c in self.lineage]) error_msg = ( - "usage: aws [options] %s " + f"usage: aws [options] {lineage} " "[parameters]\naws: error: too few arguments" - ) % lineage + ) raise ParamValidationError(error_msg) def _add_customization_to_user_agent(self): @@ -348,7 +348,7 @@ def __init__( arg_table, event_handler_class=None, ): - super(BasicHelp, self).__init__( + super().__init__( session, command_object, command_table, arg_table ) # This is defined in HelpCommand so we're matching the @@ -414,7 +414,7 @@ def __call__(self, args, parsed_globals): class BasicDocHandler(OperationDocumentEventHandler): def __init__(self, help_command): - super(BasicDocHandler, self).__init__(help_command) + super().__init__(help_command) self.doc = help_command.doc def doc_description(self, help_command, **kwargs): @@ -424,7 +424,7 @@ def doc_description(self, help_command, **kwargs): def doc_synopsis_start(self, help_command, **kwargs): if not help_command.synopsis: - super(BasicDocHandler, self).doc_synopsis_start( + super().doc_synopsis_start( help_command=help_command, **kwargs ) else: @@ -447,14 +447,14 @@ def doc_synopsis_option(self, arg_name, help_command, **kwargs): ) self._documented_arg_groups.append(argument.group_name) elif argument.cli_type_name == 'boolean': - option_str = '%s' % argument.cli_name + option_str = f'{argument.cli_name}' elif argument.nargs == '+': - option_str = "%s [...]" % argument.cli_name + option_str = f"{argument.cli_name} [...]" else: - option_str = '%s ' % argument.cli_name + option_str = f'{argument.cli_name} ' if not (argument.required or argument.positional_arg): - option_str = '[%s]' % option_str - doc.writeln('%s' % option_str) + option_str = f'[{option_str}]' + doc.writeln(f'{option_str}') else: # A synopsis has been provided so we don't need to write @@ -463,7 +463,7 @@ def doc_synopsis_option(self, arg_name, help_command, **kwargs): def doc_synopsis_end(self, help_command, **kwargs): if not help_command.synopsis and not help_command.command_table: - super(BasicDocHandler, self).doc_synopsis_end( + super().doc_synopsis_end( help_command=help_command, **kwargs ) else: diff --git a/awscli/customizations/flatten.py b/awscli/customizations/flatten.py index 9dbff925daf8..c875a058b630 100644 --- a/awscli/customizations/flatten.py +++ b/awscli/customizations/flatten.py @@ -47,7 +47,7 @@ def __init__( self._property = prop self._hydrate = hydrate self._hydrate_value = hydrate_value - super(FlattenedArgument, self).__init__( + super().__init__( name=name, help_text=help_text, required=required ) @@ -187,7 +187,7 @@ def flatten_args(self, command, argument_table, **kwargs): overwritten = False LOG.debug( - 'Flattening {0} argument {1} into {2}'.format( + 'Flattening {} argument {} into {}'.format( command.name, name, ', '.join( diff --git a/awscli/customizations/generatecliskeleton.py b/awscli/customizations/generatecliskeleton.py index 97ae1c668121..941ed3bca3f9 100644 --- a/awscli/customizations/generatecliskeleton.py +++ b/awscli/customizations/generatecliskeleton.py @@ -67,12 +67,12 @@ class GenerateCliSkeletonArgument(OverrideRequiredArgsArgument): } def __init__(self, session, operation_model): - super(GenerateCliSkeletonArgument, self).__init__(session) + super().__init__(session) self._operation_model = operation_model def _register_argument_action(self): self._session.register('calling-command.*', self.generate_skeleton) - super(GenerateCliSkeletonArgument, self)._register_argument_action() + super()._register_argument_action() def override_required_args(self, argument_table, args, **kwargs): arg_name = '--' + self.name @@ -87,7 +87,7 @@ def override_required_args(self, argument_table, args, **kwargs): return except IndexError: pass - super(GenerateCliSkeletonArgument, self).override_required_args( + super().override_required_args( argument_table, args, **kwargs ) @@ -98,7 +98,7 @@ def generate_skeleton( return arg_value = parsed_args.generate_cli_skeleton return getattr( - self, '_generate_%s_skeleton' % arg_value.replace('-', '_') + self, '_generate_{}_skeleton'.format(arg_value.replace('-', '_')) )(call_parameters=call_parameters, parsed_globals=parsed_globals) def _generate_yaml_input_skeleton(self, **kwargs): @@ -166,7 +166,7 @@ def represent(cls, dumper, data): class YAMLArgumentGenerator(ArgumentGenerator): def __init__(self, use_member_names=False, yaml=None): - super(YAMLArgumentGenerator, self).__init__( + super().__init__( use_member_names=use_member_names ) self._yaml = yaml @@ -180,7 +180,7 @@ def _generate_skeleton(self, shape, stack, name=''): # serialization output more usable on python 3. if shape.type_name == 'blob': return _Bytes() - return super(YAMLArgumentGenerator, self)._generate_skeleton( + return super()._generate_skeleton( shape, stack, name ) @@ -214,12 +214,12 @@ def _add_member_comments( skeleton.yaml_add_eol_comment('# ' + comment, member_name) def _get_enums_comment_content(self, enums): - return 'Valid values are: %s.' % ', '.join(enums) + return 'Valid values are: {}.'.format(', '.join(enums)) def _generate_type_map(self, shape, stack): # YAML has support for ordered maps, so don't use ordereddicts # because that isn't necessary and it makes the output harder to # understand and read. return dict( - super(YAMLArgumentGenerator, self)._generate_type_map(shape, stack) + super()._generate_type_map(shape, stack) ) diff --git a/awscli/customizations/globalargs.py b/awscli/customizations/globalargs.py index 94d84649eab2..fcb5ce2d6794 100644 --- a/awscli/customizations/globalargs.py +++ b/awscli/customizations/globalargs.py @@ -54,7 +54,7 @@ def resolve_types(parsed_args, **kwargs): def _resolve_arg(parsed_args, name): value = getattr(parsed_args, name, None) if value is not None: - new_value = getattr(sys.modules[__name__], '_resolve_%s' % name)(value) + new_value = getattr(sys.modules[__name__], f'_resolve_{name}')(value) setattr(parsed_args, name, new_value) @@ -63,7 +63,7 @@ def _resolve_query(value): return jmespath.compile(value) except Exception as e: raise ParamValidationError( - "Bad value for --query %s: %s" % (value, str(e)) + f"Bad value for --query {value}: {str(e)}" ) @@ -73,9 +73,9 @@ def _resolve_endpoint_url(value): # that contains a scheme, so we'll verify that up front. if not parsed.scheme: raise ParamValidationError( - 'Bad value for --endpoint-url "%s": scheme is ' + f'Bad value for --endpoint-url "{value}": scheme is ' 'missing. Must be of the form ' - 'http:/// or https:///' % value + 'http:/// or https:///' ) return value diff --git a/awscli/customizations/iamvirtmfa.py b/awscli/customizations/iamvirtmfa.py index c46fbd6ad3c9..9a90b48c3e2d 100644 --- a/awscli/customizations/iamvirtmfa.py +++ b/awscli/customizations/iamvirtmfa.py @@ -38,7 +38,7 @@ ) BOOTSTRAP_HELP = ( 'Method to use to seed the virtual MFA. ' - 'Valid values are: %s | %s' % CHOICES + 'Valid values are: {} | {}'.format(*CHOICES) ) @@ -47,7 +47,7 @@ def add_to_params(self, parameters, value): # Validate the file here so we can raise an error prior # calling the service. value = resolve_given_outfile_path(value) - super(FileArgument, self).add_to_params(parameters, value) + super().add_to_params(parameters, value) class IAMVMFAWrapper: diff --git a/awscli/customizations/opsworks.py b/awscli/customizations/opsworks.py index ac23cd5237a2..b777b1c27c76 100644 --- a/awscli/customizations/opsworks.py +++ b/awscli/customizations/opsworks.py @@ -158,7 +158,7 @@ class OpsWorksRegister(BasicCommand): ] def __init__(self, session): - super(OpsWorksRegister, self).__init__(session) + super().__init__(session) self._stack = None self._ec2_instance = None self._prov_params = None @@ -227,9 +227,9 @@ def prevalidate_arguments(self, args): if args.hostname: if not HOSTNAME_RE.match(args.hostname): raise ParamValidationError( - "Invalid hostname: '%s'. Hostnames must consist of " + f"Invalid hostname: '{args.hostname}'. Hostnames must consist of " "letters, digits and dashes only and must not start or " - "end with a dash." % args.hostname + "end with a dash." ) def retrieve_stack(self, args): @@ -302,12 +302,11 @@ def retrieve_stack(self, args): if not instances: raise ValueError( - "Did not find any instance matching %s." % args.target + f"Did not find any instance matching {args.target}." ) elif len(instances) > 1: raise ValueError( - "Found multiple instances matching %s: %s." - % ( + "Found multiple instances matching {}: {}.".format( args.target, ", ".join(i['InstanceId'] for i in instances), ) @@ -329,8 +328,8 @@ def validate_arguments(self, args): for instance in instances ): raise ValueError( - "Invalid hostname: '%s'. Hostnames must be unique within " - "a stack." % args.hostname + f"Invalid hostname: '{args.hostname}'. Hostnames must be unique within " + "a stack." ) if args.infrastructure_class == 'ec2' and args.local: @@ -397,7 +396,7 @@ def create_iam_entities(self, args): return LOG.debug("Creating the IAM group if necessary") - group_name = "OpsWorks-%s" % clean_for_iam(self._stack['StackId']) + group_name = "OpsWorks-{}".format(clean_for_iam(self._stack['StackId'])) try: self.iam.create_group(GroupName=group_name, Path=IAM_PATH) LOG.debug("Created IAM group %s", group_name) @@ -414,12 +413,12 @@ def create_iam_entities(self, args): # create the IAM user, trying alternatives if it already exists LOG.debug("Creating an IAM user") - base_username = "OpsWorks-%s-%s" % ( + base_username = "OpsWorks-{}-{}".format( shorten_name(clean_for_iam(self._stack['Name']), 25), shorten_name(clean_for_iam(self._name_for_iam), 25), ) for try_ in range(20): - username = base_username + ("+%s" % try_ if try_ else "") + username = base_username + (f"+{try_}" if try_ else "") try: self.iam.create_user(UserName=username, Path=IAM_PATH) except ClientError as e: @@ -514,12 +513,12 @@ def ssh(self, args, remote_script): else: call = 'plink' if args.username: - call += ' -l "%s"' % args.username + call += f' -l "{args.username}"' if args.private_key: - call += ' -i "%s"' % args.private_key - call += ' "%s"' % self._use_address + call += f' -i "{args.private_key}"' + call += f' "{self._use_address}"' call += ' -m' - call += ' "%s"' % script_file.name + call += f' "{script_file.name}"' subprocess.check_call(call, shell=True) finally: @@ -580,7 +579,7 @@ def _iam_policy_document(arn, timeout=None): @staticmethod def _to_ruby_yaml(parameters): return "\n".join( - ":%s: %s" % (k, json.dumps(v)) + f":{k}: {json.dumps(v)}" for k, v in sorted(parameters.items()) ) diff --git a/awscli/customizations/paginate.py b/awscli/customizations/paginate.py index bb8f31914dc4..86caef41d0f5 100644 --- a/awscli/customizations/paginate.py +++ b/awscli/customizations/paginate.py @@ -107,26 +107,24 @@ def add_paging_description(help_command, **kwargs): return help_command.doc.style.new_paragraph() help_command.doc.writeln( - ( - '``%s`` is a paginated operation. Multiple API calls may be issued ' + + f'``{help_command.name}`` is a paginated operation. Multiple API calls may be issued ' 'in order to retrieve the entire data set of results. You can ' 'disable pagination by providing the ``--no-paginate`` argument.' - ) - % help_command.name + ) # Only include result key information if it is present. if paginator_config.get('result_key'): queries = paginator_config['result_key'] if type(queries) is not list: queries = [queries] - queries = ", ".join([('``%s``' % s) for s in queries]) + queries = ", ".join([(f'``{s}``') for s in queries]) help_command.doc.writeln( - ( + 'When using ``--output text`` and the ``--query`` argument on a ' 'paginated response, the ``--query`` argument must extract data ' - 'from the results of the following query expressions: %s' - ) - % queries + f'from the results of the following query expressions: {queries}' + ) @@ -171,8 +169,8 @@ def unify_paging_params( if type_name not in PageArgument.type_map: raise TypeError( ( - 'Unsupported pagination type {0} for operation {1}' - ' and parameter {2}' + 'Unsupported pagination type {} for operation {}' + ' and parameter {}' ).format( type_name, operation_model.name, @@ -295,7 +293,7 @@ def ensure_paging_params_not_set(parsed_args, shadowed_args): ) raise ParamValidationError( "Cannot specify --no-paginate along with pagination " - "arguments: %s" % converted_params + f"arguments: {converted_params}" ) @@ -322,8 +320,7 @@ def _get_all_input_tokens(pagination_config): # Get all input tokens including the limit_key # if it exists. tokens = _get_input_tokens(pagination_config) - for token_name in tokens: - yield token_name + yield from tokens if 'limit_key' in pagination_config: key_name = pagination_config['limit_key'] yield key_name diff --git a/awscli/customizations/putmetricdata.py b/awscli/customizations/putmetricdata.py index da63967bdd8b..9e3723c57f0e 100644 --- a/awscli/customizations/putmetricdata.py +++ b/awscli/customizations/putmetricdata.py @@ -130,7 +130,7 @@ def _add_to_params(self, parameters, value): class PutMetricArgument(CustomArgument): def add_to_params(self, parameters, value): - method_name = '_add_param_%s' % self.name.replace('-', '_') + method_name = '_add_param_{}'.format(self.name.replace('-', '_')) return getattr(self, method_name)(parameters, value) @insert_first_element('MetricData') diff --git a/awscli/customizations/rekognition.py b/awscli/customizations/rekognition.py index 267376015b36..db60f6668583 100644 --- a/awscli/customizations/rekognition.py +++ b/awscli/customizations/rekognition.py @@ -36,7 +36,7 @@ def register_rekognition_detect_labels(cli): operation, old_param = target.rsplit('.', 1) doc_string_addendum = IMAGE_DOCSTRING_ADDENDUM % new_param cli.register( - 'building-argument-table.rekognition.%s' % operation, + f'building-argument-table.rekognition.{operation}', NestedBlobArgumentHoister( source_arg=old_param, source_arg_blob_member='Bytes', diff --git a/awscli/customizations/s3errormsg.py b/awscli/customizations/s3errormsg.py index e4eabf442d96..adc56ae6aae2 100644 --- a/awscli/customizations/s3errormsg.py +++ b/awscli/customizations/s3errormsg.py @@ -44,7 +44,7 @@ def enhance_error_msg(parsed, **kwargs): elif _is_permanent_redirect_message(parsed): endpoint = parsed['Error']['Endpoint'] message = parsed['Error']['Message'] - new_message = message[:-1] + ': %s\n' % endpoint + new_message = message[:-1] + f': {endpoint}\n' new_message += REGION_ERROR_MSG parsed['Error']['Message'] = new_message elif _is_kms_sigv4_error_message(parsed): diff --git a/awscli/customizations/s3events.py b/awscli/customizations/s3events.py index 2a0c31d307a7..f967862f3d66 100644 --- a/awscli/customizations/s3events.py +++ b/awscli/customizations/s3events.py @@ -59,8 +59,7 @@ def replace_event_stream_docs(help_command, **kwargs): # This should never happen, but in the rare case that it does # we should be raising something with a helpful error message. raise DocSectionNotFoundError( - 'Could not find the "output" section for the command: %s' - % help_command + f'Could not find the "output" section for the command: {help_command}' ) doc.write('======\nOutput\n======\n') doc.write( @@ -98,7 +97,7 @@ class S3SelectStreamOutputArgument(CustomArgument): _DOCUMENT_AS_REQUIRED = True def __init__(self, stream_key, session, **kwargs): - super(S3SelectStreamOutputArgument, self).__init__(**kwargs) + super().__init__(**kwargs) # This is the key in the response body where we can find the # streamed contents. self._stream_key = stream_key diff --git a/awscli/customizations/s3uploader.py b/awscli/customizations/s3uploader.py index 3b567d1e6909..3eece5589192 100644 --- a/awscli/customizations/s3uploader.py +++ b/awscli/customizations/s3uploader.py @@ -223,12 +223,6 @@ def on_progress(self, future, bytes_transferred, **kwargs): self._seen_so_far += bytes_transferred percentage = (self._seen_so_far / self._size) * 100 sys.stderr.write( - "\rUploading to %s %s / %s (%.2f%%)" - % ( - self._remote_path, - self._seen_so_far, - self._size, - percentage, - ) + f"\rUploading to {self._remote_path} {self._seen_so_far} / {self._size} ({percentage:.2f}%)" ) sys.stderr.flush() diff --git a/awscli/customizations/sessendemail.py b/awscli/customizations/sessendemail.py index ea290a63b685..350118d03e96 100644 --- a/awscli/customizations/sessendemail.py +++ b/awscli/customizations/sessendemail.py @@ -109,7 +109,7 @@ def __init__( choices=None, cli_type_name=None, ): - super(AddressesArgument, self).__init__( + super().__init__( name=name, help_text=help_text, required=required, nargs='+' ) self._json_key = json_key @@ -121,7 +121,7 @@ def add_to_params(self, parameters, value): class BodyArgument(CustomArgument): def __init__(self, name, json_key, help_text='', required=None): - super(BodyArgument, self).__init__( + super().__init__( name=name, help_text=help_text, required=required ) self._json_key = json_key diff --git a/awscli/customizations/sessionmanager.py b/awscli/customizations/sessionmanager.py index 16e0868cb0e2..f5c29fcb8010 100644 --- a/awscli/customizations/sessionmanager.py +++ b/awscli/customizations/sessionmanager.py @@ -86,7 +86,7 @@ def _normalize(self, v1, v2): class StartSessionCommand(ServiceOperation): def create_help_command(self): - help_command = super(StartSessionCommand, self).create_help_command() + help_command = super().create_help_command() # Change the output shape because the command provides no output. self._operation_model.output_shape = None return help_command diff --git a/awscli/customizations/streamingoutputarg.py b/awscli/customizations/streamingoutputarg.py index c4decbb6844d..0eea2ca79214 100644 --- a/awscli/customizations/streamingoutputarg.py +++ b/awscli/customizations/streamingoutputarg.py @@ -92,7 +92,7 @@ def add_to_params(self, parameters, value): service_id = self._operation_model.service_model.service_id.hyphenize() operation_name = self._operation_model.name self._session.register( - 'after-call.%s.%s' % (service_id, operation_name), self.save_file + f'after-call.{service_id}.{operation_name}', self.save_file ) def save_file(self, parsed, **kwargs): diff --git a/awscli/customizations/timestampformat.py b/awscli/customizations/timestampformat.py index efc765668b68..b2f094a5decd 100644 --- a/awscli/customizations/timestampformat.py +++ b/awscli/customizations/timestampformat.py @@ -74,7 +74,7 @@ def add_timestamp_parser(session, **kwargs): timestamp_parser = iso_format else: raise ConfigurationError( - 'Unknown cli_timestamp_format value: %s, valid values' - ' are "wire" or "iso8601"' % timestamp_format + f'Unknown cli_timestamp_format value: {timestamp_format}, valid values' + ' are "wire" or "iso8601"' ) factory.set_parser_defaults(timestamp_parser=timestamp_parser) diff --git a/awscli/customizations/toplevelbool.py b/awscli/customizations/toplevelbool.py index 826d6c5ccb04..22f15457a164 100644 --- a/awscli/customizations/toplevelbool.py +++ b/awscli/customizations/toplevelbool.py @@ -76,14 +76,14 @@ def pull_up_bool(argument_table, event_handler, **kwargs): serialized_name=value._serialized_name, ) argument_table[value.name] = new_arg - negative_name = 'no-%s' % value.name + negative_name = f'no-{value.name}' negative_arg = NegativeBooleanParameter( negative_name, arg_model, value._operation_model, value._event_emitter, action='store_true', - dest='no_%s' % new_arg.py_name, + dest=f'no_{new_arg.py_name}', group_name=value.name, serialized_name=value._serialized_name, ) @@ -104,8 +104,8 @@ def validate_boolean_mutex_groups(boolean_pairs, parsed_args, **kwargs): and getattr(parsed_args, negative.py_name) is not _NOT_SPECIFIED ): raise ParamValidationError( - 'Cannot specify both the "%s" option and ' - 'the "%s" option.' % (positive.cli_name, negative.cli_name) + f'Cannot specify both the "{positive.cli_name}" option and ' + f'the "{negative.cli_name}" option.' ) @@ -119,7 +119,7 @@ def __init__( serialized_name, group_name, ): - super(PositiveBooleanArgument, self).__init__( + super().__init__( name, argument_model, operation_model, @@ -171,7 +171,7 @@ def __init__( dest=None, group_name=None, ): - super(NegativeBooleanParameter, self).__init__( + super().__init__( name, argument_model, operation_model, diff --git a/awscli/customizations/utils.py b/awscli/customizations/utils.py index fd135a8714a2..60b9cd68919d 100644 --- a/awscli/customizations/utils.py +++ b/awscli/customizations/utils.py @@ -114,9 +114,9 @@ def validate_mutually_exclusive(parsed_args, *groups): current_group = key_group elif not key_group == current_group: raise ParamValidationError( - 'The key "%s" cannot be specified when one ' + 'The key "{}" cannot be specified when one ' 'of the following keys are also specified: ' - '%s' % (key, ', '.join(current_group)) + '{}'.format(key, ', '.join(current_group)) ) @@ -239,7 +239,7 @@ def _strip_xml_from_documentation(documentation): # to make sure the dom parser will look at all elements in the # docstring as some docstrings may not have xml nodes that do # not all belong to the same root node. - xml_doc = '%s' % documentation + xml_doc = f'{documentation}' xml_dom = xml.dom.minidom.parseString(xml_doc) except xml.parsers.expat.ExpatError: return documentation diff --git a/awscli/customizations/waiters.py b/awscli/customizations/waiters.py index a5ce1d9590a7..b02d5e45fcbe 100644 --- a/awscli/customizations/waiters.py +++ b/awscli/customizations/waiters.py @@ -69,7 +69,7 @@ def __init__(self, session, waiter_model, service_model): model=self._model, service_model=self._service_model, ) - super(WaitCommand, self).__init__(session) + super().__init__(session) def _run_main(self, parsed_args, parsed_globals): if parsed_args.subcommand is None: @@ -77,7 +77,7 @@ def _run_main(self, parsed_args, parsed_globals): return 0 def _build_subcommand_table(self): - subcommand_table = super(WaitCommand, self)._build_subcommand_table() + subcommand_table = super()._build_subcommand_table() self.waiter_cmd_builder.build_all_waiter_state_cmds(subcommand_table) self._add_lineage(subcommand_table) return subcommand_table @@ -187,7 +187,7 @@ def _build_success_description(self, acceptor): # description about what resource is looked at. if matcher in ['path', 'pathAny', 'pathAll']: resource_description = ( - 'JMESPath query %s returns ' % acceptor.argument + f'JMESPath query {acceptor.argument} returns ' ) # Prepend the resource description to the template description success_description = resource_description + success_description @@ -197,13 +197,13 @@ def _build_success_description(self, acceptor): def _build_operation_description(self, operation): operation_name = xform_name(operation).replace('_', '-') - return 'when polling with ``%s``.' % operation_name + return f'when polling with ``{operation_name}``.' def _build_polling_description(self, delay, max_attempts): description = ( - ' It will poll every %s seconds until a successful state ' + f' It will poll every {delay} seconds until a successful state ' 'has been reached. This will exit with a return code of 255 ' - 'after %s failed checks.' % (delay, max_attempts) + f'after {max_attempts} failed checks.' ) return description @@ -229,7 +229,7 @@ class WaiterStateCommand(ServiceOperation): DESCRIPTION = '' def create_help_command(self): - help_command = super(WaiterStateCommand, self).create_help_command() + help_command = super().create_help_command() # Change the operation object's description by changing it to the # description for a waiter state command. self._operation_model.documentation = self.DESCRIPTION