Switching to f-strings where appropriate

This commit is contained in:
2Shirt 2019-08-20 16:00:08 -06:00
parent b314a9f1e2
commit c43539a92d
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C
3 changed files with 25 additions and 42 deletions

View file

@ -1,7 +1,7 @@
'''WizardKit: wk module init''' '''WizardKit: wk module init'''
# vim: sts=2 sw=2 ts=2 # vim: sts=2 sw=2 ts=2
import sys from sys import version_info as version
from wk import cfg from wk import cfg
from wk import exe from wk import exe
@ -16,12 +16,11 @@ from wk import sw
# Check env # Check env
if sys.version_info < (3, 7): if version < (3, 7):
# Unsupported # Unsupported
raise RuntimeError( raise RuntimeError(
'This package is unsupported on Python {major}.{minor}'.format( f'This package is unsupported on Python {version.major}.{version.minor}'
**sys.version_info, )
))
# Init # Init
try: try:

View file

@ -69,16 +69,13 @@ def update_log_path(dest_dir, dest_name=''):
dest = pathlib.Path(dest_dir) dest = pathlib.Path(dest_dir)
dest = dest.expanduser() dest = dest.expanduser()
if dest_name: if dest_name:
dest_name = '{name}_{datetime}.log'.format( dest_name = f'{dest_name}_{time.strftime("%Y-%m-%d_%H%M%S%z")}.log'
name=dest_name,
datetime=time.strftime('%Y-%m-%d_%H%M%S%z'),
)
# Safety checks # Safety checks
if len(root_logger.handlers) > 1: if len(root_logger.handlers) > 1:
raise NotImplementedError('update_log_path() only supports a single handler.') raise NotImplementedError('Multiple handlers not supported')
if not isinstance(cur_handler, logging.FileHandler): if not isinstance(cur_handler, logging.FileHandler):
raise NotImplementedError('update_log_path() only supports FileHandlers.') raise NotImplementedError('Only FileHandlers are supported')
# Copy original log to new location # Copy original log to new location
source = pathlib.Path(cur_handler.baseFilename) source = pathlib.Path(cur_handler.baseFilename)
@ -89,7 +86,7 @@ def update_log_path(dest_dir, dest_name=''):
dest = dest.joinpath(source.name) dest = dest.joinpath(source.name)
dest = dest.resolve() dest = dest.resolve()
if dest.exists(): if dest.exists():
raise FileExistsError('Refusing to clobber: {}'.format(dest)) raise FileExistsError(f'Refusing to clobber: {dest}')
os.makedirs(dest.parent, exist_ok=True) os.makedirs(dest.parent, exist_ok=True)
shutil.copy(source, dest) shutil.copy(source, dest)

View file

@ -1,6 +1,5 @@
'''WizardKit: Standard Functions''' '''WizardKit: Standard Functions'''
# vim: sts=2 sw=2 ts=2 # vim: sts=2 sw=2 ts=2
#TODO Replace .format()s with f-strings
import itertools import itertools
import logging import logging
@ -74,7 +73,7 @@ def abort(prompt='Aborted.', show_prompt=True, return_code=1):
def ask(prompt='Kotaero!'): def ask(prompt='Kotaero!'):
"""Prompt the user with a Y/N question, returns bool.""" """Prompt the user with a Y/N question, returns bool."""
answer = None answer = None
prompt = '{} [Y/N]: '.format(prompt) prompt = f'{prompt} [Y/N]: '
# Loop until acceptable answer is given # Loop until acceptable answer is given
while answer is None: while answer is None:
@ -135,12 +134,8 @@ def bytes_to_string(size, decimals=0, use_binary=True):
units = 'K' + suffix units = 'K' + suffix
else: else:
size /= scale ** 0 size /= scale ** 0
units = ' {}B'.format(' ' if use_binary else '') units = f' {" " if use_binary else ""}B'
size = '{size:0.{decimals}f} {units}'.format( size = f'{size:0.{decimals}f} {units}'
size=size,
decimals=decimals,
units=units,
)
# Done # Done
LOG.debug('string: %s', size) LOG.debug('string: %s', size)
@ -156,8 +151,8 @@ def choice(choices, prompt='答えろ!'):
LOG.debug('choices: %s, prompt: %s', choices, prompt) LOG.debug('choices: %s, prompt: %s', choices, prompt)
answer = None answer = None
choices = [str(c).upper()[:1] for c in choices] choices = [str(c).upper()[:1] for c in choices]
prompt = '{} [{}]: '.format(prompt, '/'.join(choices)) prompt = f'{prompt} [{"/".join(choices)}]'
regex = '^({})$'.format('|'.join(choices)) regex = f'^({"|".join(choices)})$'
# Loop until acceptable answer is given # Loop until acceptable answer is given
while answer is None: while answer is None:
@ -316,18 +311,18 @@ def generate_debug_report():
report.append('--- Start debug info ---') report.append('--- Start debug info ---')
report.append('') report.append('')
report.append('[System]') report.append('[System]')
report.append(' {:<24} {}'.format('FQDN', socket.getfqdn())) report.append(f' {"FQDN":<24} {socket.getfqdn()}')
for func in platform_function_list: for func in platform_function_list:
func_name = func.replace('_', ' ').capitalize() func_name = func.replace('_', ' ').capitalize()
func_result = getattr(platform, func)() func_result = getattr(platform, func)()
report.append(' {:<24} {}'.format(func_name, func_result)) report.append(f' {func_name:<24} {func_result}')
report.append(' {:<24} {}'.format('Python sys.argv', sys.argv)) report.append(f' {"Python sys.argv":<24} {sys.argv}')
report.append('') report.append('')
# Environment # Environment
report.append('[Environment Variables]') report.append('[Environment Variables]')
for key, value in sorted(os.environ.items()): for key, value in sorted(os.environ.items()):
report.append(' {:<24} {}'.format(key, value)) report.append(f' {key:<24} {value}')
report.append('') report.append('')
# Done # Done
@ -368,9 +363,7 @@ def major_exception():
report = generate_debug_report() report = generate_debug_report()
# Upload details # Upload details
prompt = 'Upload details to {}?'.format( prompt = f'Upload details to {CRASH_SERVER.get("Name", "?")}?'
CRASH_SERVER.get('Name', '?'),
)
if ENABLED_UPLOAD_DATA and ask(prompt): if ENABLED_UPLOAD_DATA and ask(prompt):
print('Uploading... ', end='', flush=True) print('Uploading... ', end='', flush=True)
try: try:
@ -395,6 +388,7 @@ def pause(prompt='Press Enter to continue... '):
def print_colored(strings, colors, **kwargs): def print_colored(strings, colors, **kwargs):
"""Prints strings in the colors specified.""" """Prints strings in the colors specified."""
LOG.debug('strings: %s, colors: %s, kwargs: %s', strings, colors, kwargs) LOG.debug('strings: %s, colors: %s, kwargs: %s', strings, colors, kwargs)
clear_code = COLORS['CLEAR']
msg = '' msg = ''
print_options = { print_options = {
'end': kwargs.get('end', '\n'), 'end': kwargs.get('end', '\n'),
@ -404,11 +398,8 @@ def print_colored(strings, colors, **kwargs):
# Build new string with color escapes added # Build new string with color escapes added
for string, color in itertools.zip_longest(strings, colors): for string, color in itertools.zip_longest(strings, colors):
msg += '{}{}{}'.format( color_code = COLORS.get(color, clear_code)
COLORS.get(color, COLORS['CLEAR']), msg += f'{color_code}{string}{clear_code}'
string,
COLORS['CLEAR'],
)
print(msg, **print_options) print(msg, **print_options)
@ -446,7 +437,7 @@ def print_warning(msg, **kwargs):
def set_title(title): def set_title(title):
"""Set window title.""" """Set window title."""
if os.name == 'nt': if os.name == 'nt':
os.system('title {}'.format(title)) os.system(f'title {title}')
else: else:
raise NotImplementedError raise NotImplementedError
@ -465,7 +456,7 @@ def string_to_bytes(size, assume_binary=False):
# Raise exception if string can't be parsed as a size # Raise exception if string can't be parsed as a size
if not tmp: if not tmp:
raise ValueError('Invalid size string: {}'.format(size)) raise ValueError(f'Invalid size string: {size}')
# Set scale # Set scale
if tmp.group('binary') or assume_binary: if tmp.group('binary') or assume_binary:
@ -606,11 +597,7 @@ def upload_debug_report(report, compress=True, reason='DEBUG'):
if log_path: if log_path:
# Strip everything but the prefix # Strip everything but the prefix
filename = re.sub(r'^(.*)_(\d{4}-\d{2}-\d{2}.*)', r'\1', log_path.name) filename = re.sub(r'^(.*)_(\d{4}-\d{2}-\d{2}.*)', r'\1', log_path.name)
filename = '{prefix}_{reason}_{datetime}.log'.format( filename = f'{filename}_{reason}_{time.strftime("%Y-%m-%d_%H%M%S%z")}.log'
prefix=filename,
reason=reason,
datetime=time.strftime('%Y-%m-%d_%H%M%S%z'),
)
LOG.debug('filename: %s', filename) LOG.debug('filename: %s', filename)
# Compress report # Compress report
@ -619,7 +606,7 @@ def upload_debug_report(report, compress=True, reason='DEBUG'):
xz_report = lzma.compress(report.encode('utf8')) xz_report = lzma.compress(report.encode('utf8'))
# Upload report # Upload report
url = '{}/{}'.format(CRASH_SERVER['Url'], filename) url = f'{CRASH_SERVER["Url"]}/{filename}'
response = requests.put( response = requests.put(
url, url,
data=xz_report if compress else report, data=xz_report if compress else report,