diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8d382e324..a20d098c7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,6 +16,7 @@ repos: rev: v2.10.0 hooks: - id: pyupgrade + args: ["--py37-plus"] - repo: https://github.com/OctoPrint/codemods rev: 0.4.0 hooks: diff --git a/setup.py b/setup.py index c0abd505c..04aa9ae42 100644 --- a/setup.py +++ b/setup.py @@ -134,7 +134,7 @@ def md_to_html_build_py_factory(files, baseclass): source = entry dest = os.path.join(target_dir, source + ".html") - print("Rendering markdown from {} to {}".format(source, dest)) + print(f"Rendering markdown from {source} to {dest}") from markdown import markdownFromFile diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index d9fff3dce..1a0ee47f4 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -import io import logging as log import os import sys @@ -356,7 +355,7 @@ def init_logging( if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with io.open(logging_file, "rt", encoding="utf-8") as f: + with open(logging_file, encoding="utf-8") as f: config_from_file = yaml.safe_load(f) # we merge that with the default config @@ -386,7 +385,7 @@ def octoprint_plugin_inject_factory(settings, components): def wrapper(*args, **kwargs): tags = kwargs.get("tags", set()) | { "source:plugin", - "plugin:{}".format(name), + f"plugin:{name}", } kwargs["tags"] = tags return f(*args, **kwargs) @@ -511,7 +510,7 @@ def init_custom_events(plugin_manager): if isinstance(result, (list, tuple)): for event in result: constant, value = octoprint.events.Events.register_event( - event, prefix="plugin_{}_".format(name) + event, prefix=f"plugin_{name}_" ) logger.debug( 'Registered event {} of plugin {} as Events.{} = "{}"'.format( @@ -520,7 +519,7 @@ def init_custom_events(plugin_manager): ) except Exception: logger.exception( - "Error while retrieving custom event list from plugin {}".format(name), + f"Error while retrieving custom event list from plugin {name}", extra={"plugin": name}, ) @@ -647,7 +646,7 @@ def init_pluginsystem( disabled_from_overlays[name] = (disabled_plugins, order) settings_overlays[name] = overlay - logger.debug("Found settings overlay on plugin {}".format(name)) + logger.debug(f"Found settings overlay on plugin {name}") def handle_plugins_loaded( startup=False, initialize_implementations=True, force_reload=None @@ -689,7 +688,7 @@ def init_pluginsystem( def handle_plugin_enabled(name, plugin): if name in settings_overlays: settings.add_overlay(settings_overlays[name]) - logger.info("Added settings overlay from plugin {}".format(name)) + logger.info(f"Added settings overlay from plugin {name}") pm.on_plugin_loaded = handle_plugin_loaded pm.on_plugins_loaded = handle_plugins_loaded @@ -718,7 +717,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): format_entry = ( lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 - else "{} (any)".format(x) + else f"{x} (any)" ) return ", ".join(map(format_entry, entries)) diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 77b78b683..bff3b84f6 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -10,7 +10,6 @@ """Git implementation of _version.py.""" import errno -import io import logging import os import re @@ -97,7 +96,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): return None else: if verbose: - print("unable to find command, tried {}".format(commands)) + print(f"unable to find command, tried {commands}") return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: @@ -140,7 +139,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = io.open(versionfile_abs, "rt", encoding="utf-8") + f = open(versionfile_abs, encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -334,7 +333,7 @@ def git_parse_lookup_file(path): import re lookup = [] - with io.open(path, "rt", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: for line in f: if "#" in line: line = line[: line.index("#")] diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index d63363ff6..00c6f0d41 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -2,7 +2,6 @@ __author__ = "Marc Hannappel " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os from functools import partial @@ -183,13 +182,13 @@ class GroupManager: return None def _notify_listeners(self, action, group, *args, **kwargs): - method = "on_group_{}".format(action) + method = f"on_group_{action}" for listener in self._group_change_listeners: try: getattr(listener, method)(group, *args, **kwargs) except Exception: self._logger.exception( - "Error notifying listener {!r} via {}".format(listener, method) + f"Error notifying listener {listener!r} via {method}" ) @@ -227,7 +226,7 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with io.open(self._groupfile, "rt", encoding="utf-8") as f: + with open(self._groupfile, encoding="utf-8") as f: data = yaml.safe_load(f) if "groups" not in data: @@ -316,7 +315,7 @@ class FilebasedGroupManager(GroupManager): except Exception: self._logger.exception( - "Error while loading groups from file {}".format(self._groupfile) + f"Error while loading groups from file {self._groupfile}" ) def _save(self, force=False): diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index feacd6722..a327bf22f 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import hashlib -import io import logging import os import time @@ -83,11 +82,11 @@ class UserManager(GroupChangeListener): listener.on_user_logged_in(user) except Exception: self._logger.exception( - "Error in on_user_logged_in on {!r}".format(listener), + f"Error in on_user_logged_in on {listener!r}", extra={"callback": fqcn(listener)}, ) - self._logger.info("Logged in user: {}".format(user.get_id())) + self._logger.info(f"Logged in user: {user.get_id()}") return user @@ -121,11 +120,11 @@ class UserManager(GroupChangeListener): listener.on_user_logged_out(user, stale=stale) except Exception: self._logger.exception( - "Error in on_user_logged_out on {!r}".format(listener), + f"Error in on_user_logged_out on {listener!r}", extra={"callback": fqcn(listener)}, ) - self._logger.info("Logged out user: {}".format(user.get_id())) + self._logger.info(f"Logged out user: {user.get_id()}") def _cleanup_sessions(self): for session, user in list(self._session_users_by_session.items()): @@ -269,9 +268,7 @@ class UserManager(GroupChangeListener): return False def on_group_removed(self, group): - self._logger.debug( - "Group {} got removed, removing from all users".format(group.key) - ) + self._logger.debug(f"Group {group.key} got removed, removing from all users") self.remove_groups_from_users([group]) def on_group_permissions_changed(self, group, added=None, removed=None): @@ -282,7 +279,7 @@ class UserManager(GroupChangeListener): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -295,7 +292,7 @@ class UserManager(GroupChangeListener): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -327,7 +324,7 @@ class UserManager(GroupChangeListener): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -337,7 +334,7 @@ class UserManager(GroupChangeListener): listener.on_user_removed(username) except Exception: self._logger.exception( - "Error in on_user_removed on {!r}".format(listener), + f"Error in on_user_removed on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -516,7 +513,7 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): # noinspection PyBroadException - with io.open(self._userfile, "rt", encoding="utf-8") as f: + with open(self._userfile, encoding="utf-8") as f: data = yaml.safe_load(f) if not data or not isinstance(data, dict): diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index a1fedb377..151de614d 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -113,7 +113,7 @@ def gcode_command( if progress: def progress_callback(percentage): - click.echo("PROGRESS:{}".format(percentage)) + click.echo(f"PROGRESS:{percentage}") interpreter = gcode(progress_callback=progress_callback) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index e0d6f809f..212485e66 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import json import os @@ -45,11 +44,11 @@ def create_client( if not apikey: cli_key_file = os.path.join(settings.getBaseFolder("generated"), "cli.key") try: - with io.open(cli_key_file, "r", encoding="utf8") as f: + with open(cli_key_file, encoding="utf8") as f: apikey = f.readline() except Exception: raise FatalStartupError( - "Can not authenticate with server at {}:{}, no key".format(host, port) + f"Can not authenticate with server at {host}:{port}, no key" ) baseurl = octoprint_client.build_base_url( @@ -115,10 +114,10 @@ def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): def log_response(response, status_code=True, body=True, headers=False): if status_code: - click.echo("Status Code: {}".format(response.status_code)) + click.echo(f"Status Code: {response.status_code}") if headers: for header, value in response.headers.items(): - click.echo("{}: {}".format(header, value)) + click.echo(f"{header}: {value}") click.echo() if body: click.echo(response.text) @@ -169,17 +168,17 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: - with io.open(file_path, "rt") as fp: + with open(file_path) as fp: data = json.load(fp) else: import yaml - with io.open(file_path, "rt") as fp: + with open(file_path) as fp: data = yaml.safe_load(fp) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: - with io.open(file_path, "rb") as fp: + with open(file_path, "rb") as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) @@ -285,7 +284,7 @@ def listen(ctx): click.echo("--- Connection closed!") def on_error(ws, error): - click.echo("!!! Error: {}".format(error)) + click.echo(f"!!! Error: {error}") def on_sent(ws, data): click.echo(">>> {}".format(json.dumps(data))) diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 7da5de9c6..394450670 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -33,9 +33,7 @@ class OctoPrintDevelCommands(click.MultiCommand): return log self.command_caller = CommandlineCaller() - self.command_caller.on_log_call = log_util( - lambda x: click.echo(">> {}".format(x)) - ) + self.command_caller.on_log_call = log_util(lambda x: click.echo(f">> {x}")) self.command_caller.on_log_stdout = log_util(click.echo) self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) @@ -53,7 +51,7 @@ class OctoPrintDevelCommands(click.MultiCommand): def _get_commands(self): result = {} for group in self.groups: - for command in self._get_commands_from_prefix_methods("{}_".format(group)): + for command in self._get_commands_from_prefix_methods(f"{group}_"): result[group + self.sep + command.name] = command return result diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index 72d750bf1..642d7f431 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -131,7 +131,7 @@ class OctoPrintPluginCommands(click.MultiCommand): result[name + self.sep + command.name] = command except Exception: self._logger.exception( - "Error while retrieving cli commands for plugin {}".format(name), + f"Error while retrieving cli commands for plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 16622e2d7..6f48bb3af 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -44,7 +44,7 @@ def run_server( PluginTimingsLogHandler.arm_rollover() logger.info(get_divider_line("*")) - logger.info("Starting OctoPrint {}".format(__display_version__)) + logger.info(f"Starting OctoPrint {__display_version__}") if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") if safe_mode == "flag": @@ -55,7 +55,7 @@ def run_server( reason = "problem during last startup" else: reason = "unknown" - logger.info("Reason for safe mode: {}".format(reason)) + logger.info(f"Reason for safe mode: {reason}") if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -98,7 +98,7 @@ def run_server( log_to_handler(logger, handler, level, message) _log(get_divider_line("-", "Log roll over detected")) - _log("OctoPrint {}".format(__display_version__)) + _log(f"OctoPrint {__display_version__}") if safe_mode: _log("SAFE MODE is active. Third party plugins are disabled!") plugin_manager.log_all_plugins(only_to_handler=handler) diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index 75fe2e773..ccbb66edd 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -135,7 +135,7 @@ def systeminfo_command(ctx, path, **kwargs): if path: # create zip at path zipfilename = os.path.join(path, get_systeminfo_bundle_name()) - click.echo("Writing systeminfo bundle to {}...".format(zipfilename)) + click.echo(f"Writing systeminfo bundle to {zipfilename}...") z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs")) try: @@ -144,9 +144,7 @@ def systeminfo_command(ctx, path, **kwargs): f.write(data) except Exception as e: click.echo(str(e), err=True) - click.echo( - "There was an error writing to {}.".format(zipfilename), err=True - ) + click.echo(f"There was an error writing to {zipfilename}.", err=True) ctx.exit(-1) click.echo("Done!") diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 373ab1d95..b172548c8 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -130,9 +130,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin): click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.as_dict()))) except UserAlreadyExists: - click.echo( - "A user with the name {} does already exist!".format(username), err=True - ) + click.echo(f"A user with the name {username} does already exist!", err=True) @user.command(name="remove") @@ -147,9 +145,9 @@ def remove_user_command(ctx, username): if confirm.lower() == "yes": ctx.obj.user_manager.remove_user(username) - click.echo("User {} removed.".format(username)) + click.echo(f"User {username} removed.") else: - click.echo("User {} not removed.".format(username)) + click.echo(f"User {username} not removed.") @user.command(name="password") @@ -160,9 +158,9 @@ def change_password_command(ctx, username, password): """Change an existing user's password.""" try: ctx.obj.user_manager.change_user_password(username, password) - click.echo("Password changed for user {}.".format(username)) + click.echo(f"Password changed for user {username}.") except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) @user.command(name="activate") @@ -172,14 +170,14 @@ def activate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, True) - click.echo("User {} activated.".format(username)) + click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.asDict()))) except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) @user.command(name="deactivate") @@ -189,14 +187,14 @@ def deactivate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, False) - click.echo("User {} activated.".format(username)) + click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.asDict()))) except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) def _print_list(users): diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 7548e23c2..07ac5d091 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -4,7 +4,6 @@ Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ -import io import os import signal import sys @@ -63,9 +62,9 @@ class Daemon: # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() - si = io.open(os.devnull, "rt", encoding="utf-8") - so = io.open(os.devnull, "at+", encoding="utf-8") - se = io.open(os.devnull, "at+", encoding="utf-8") + si = open(os.devnull, encoding="utf-8") + so = open(os.devnull, "at+", encoding="utf-8") + se = open(os.devnull, "at+", encoding="utf-8") os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) @@ -153,7 +152,7 @@ class Daemon: def get_pid(self): """Get the pid from the pidfile.""" try: - with io.open(self.pidfile, "rt", encoding="utf-8") as pf: + with open(self.pidfile, encoding="utf-8") as pf: pid = int(pf.read().strip()) except (OSError, ValueError): pid = None @@ -161,7 +160,7 @@ class Daemon: def set_pid(self, pid): """Write the pid to the pidfile.""" - with io.open(self.pidfile, "wt+", encoding="utf-8") as f: + with open(self.pidfile, "wt+", encoding="utf-8") as f: f.write(str(pid) + "\n") def remove_pidfile(self): diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 59e7cd65f..6711dc02b 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -169,7 +169,7 @@ class EnvironmentDetector: environment, default_flow_style=False, indent=2, allow_unicode=True ).strip() environment_lines = "\n".join( - map(lambda l: "| {}".format(l), dumped_environment.split("\n")) + map(lambda l: f"| {l}", dumped_environment.split("\n")) ) return "Detected environment is Python {} under {} ({}). Details:\n{}".format( environment["python"]["version"], diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 3e3aa0325..f93553ee9 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -160,7 +160,7 @@ class EventManager: def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) - self._logger_fire = logging.getLogger("{}.fire".format(__name__)) + self._logger_fire = logging.getLogger(f"{__name__}.fire") self._startup_signaled = False self._shutdown_signaled = False @@ -184,12 +184,10 @@ class EventManager: self._shutdown_signaled = True eventListeners = self._registeredListeners[event] - self._logger_fire.debug( - "Firing event: {} (Payload: {!r})".format(event, payload) - ) + self._logger_fire.debug(f"Firing event: {event} (Payload: {payload!r})") for listener in eventListeners: - self._logger.debug("Sending action to {!r}".format(listener)) + self._logger.debug(f"Sending action to {listener!r}") try: listener(event, payload) except Exception: @@ -256,9 +254,7 @@ class EventManager: return self._registeredListeners[event].append(callback) - self._logger.debug( - "Subscribed listener {!r} for event {}".format(callback, event) - ) + self._logger.debug(f"Subscribed listener {callback!r} for event {event}") def unsubscribe(self, event, callback): """ @@ -317,7 +313,7 @@ class DebugEventListener(GenericEventListener): def eventCallback(self, event, payload): GenericEventListener.eventCallback(self, event, payload) - self._logger.debug("Received event: {} (Payload: {!r})".format(event, payload)) + self._logger.debug(f"Received event: {event} (Payload: {payload!r})") class CommandTrigger(GenericEventListener): @@ -364,7 +360,7 @@ class CommandTrigger(GenericEventListener): continue if "enabled" in subscription and not subscription["enabled"]: - self._logger.info("Disabled command trigger: {!r}".format(subscription)) + self._logger.info(f"Disabled command trigger: {subscription!r}") continue events = subscription["event"] @@ -423,7 +419,7 @@ class CommandTrigger(GenericEventListener): def _executeSystemCommand(self, command, debug=False): def commandExecutioner(cmd): if debug: - self._logger.info("Executing system command: {}".format(cmd)) + self._logger.info(f"Executing system command: {cmd}") else: self._logger.info("Executing a system command") # we run this with shell=True since we have to trust whatever diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 757617677..555d9c358 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -445,8 +445,6 @@ class FileManager: source_meta = self.get_metadata(source_location, source_path) hash = source_meta.get("hash", "n/a") - import io - links = [("model", {"name": source_path})] _, stl_name = self.split_path(source_location, source_path) file_obj = StreamWrapper( @@ -954,7 +952,7 @@ class FileManager: ) except Exception: self._logger.exception( - "Could not write recovery data to file {}".format(self._recovery_file) + f"Could not write recovery data to file {self._recovery_file}" ) def delete_recovery_data(self): @@ -965,7 +963,7 @@ class FileManager: os.remove(self._recovery_file) except Exception: self._logger.exception( - "Error deleting recovery data file {}".format(self._recovery_file) + f"Error deleting recovery data file {self._recovery_file}" ) def get_recovery_data(self): @@ -975,7 +973,7 @@ class FileManager: import yaml try: - with io.open(self._recovery_file, "rt", encoding="utf-8") as f: + with open(self._recovery_file, encoding="utf-8") as f: data = yaml.safe_load(f) if not isinstance(data, dict) or not all( map(lambda x: x in data, ("origin", "path", "pos", "date")) @@ -984,7 +982,7 @@ class FileManager: return data except Exception: self._logger.exception( - "Could not read recovery data from file {}".format(self._recovery_file) + f"Could not read recovery data from file {self._recovery_file}" ) self.delete_recovery_data() diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index af9cad273..0391fd513 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -39,7 +39,7 @@ class QueueEntry( """ def __str__(self): - return "{location}:{path}".format(location=self.location, path=self.path) + return f"{self.location}:{self.path}" class AnalysisAborted(Exception): @@ -114,7 +114,7 @@ class AnalysisQueue: callback(entry, result) except Exception: self._logger.exception( - "Error while pushing analysis data to callback {}".format(callback), + f"Error while pushing analysis data to callback {callback}", extra={"callback": fqcn(callback)}, ) eventManager().fire( @@ -185,9 +185,7 @@ class AbstractAnalysisQueue: """ if settings().get(["gcodeAnalysis", "runAt"]) == "never": - self._logger.debug( - "Ignoring entry {entry} for analysis queue".format(entry=entry) - ) + self._logger.debug(f"Ignoring entry {entry} for analysis queue") return elif high_priority: self._logger.debug( @@ -254,7 +252,7 @@ class AbstractAnalysisQueue: while True: (priority, entry, high_priority) = self._queue.get() self._logger.debug( - "Processing entry {} from queue (priority {})".format(entry, priority) + f"Processing entry {entry} from queue (priority {priority})" ) self._active.wait() @@ -273,7 +271,7 @@ class AbstractAnalysisQueue: high_priority, ) ) - self._logger.debug("Running analysis of entry {} aborted".format(entry)) + self._logger.debug(f"Running analysis of entry {entry} aborted") self._queue.task_done() self._done.set() else: @@ -290,7 +288,7 @@ class AbstractAnalysisQueue: try: start_time = time.monotonic() - self._logger.info("Starting analysis of {}".format(entry)) + self._logger.info(f"Starting analysis of {entry}") eventManager().fire( Events.METADATA_ANALYSIS_STARTED, { @@ -311,9 +309,7 @@ class AbstractAnalysisQueue: ) self._finished_callback(self._current, result) except RuntimeError as exc: - self._logger.error( - "Analysis for {} ran into error: {}".format(self._current, exc) - ) + self._logger.error(f"Analysis for {self._current} ran into error: {exc}") finally: self._current = None self._current_progress = None @@ -421,12 +417,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): "octoprint", "analysis", "gcode", - "--speed-x={}".format(speedx), - "--speed-y={}".format(speedy), - "--max-t={}".format(max_extruders), - "--throttle={}".format(throttle), - "--throttle-lines={}".format(throttle_lines), - "--bed-z={}".format(bed_z), + f"--speed-x={speedx}", + f"--speed-y={speedy}", + f"--max-t={max_extruders}", + f"--throttle={throttle}", + f"--throttle-lines={throttle_lines}", + f"--bed-z={bed_z}", ] for offset in offsets[1:]: command += ["--offset", str(offset[0]), str(offset[1])] @@ -472,7 +468,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): p.close() output = p.stdout.text - self._logger.debug("Got output: {!r}".format(output)) + self._logger.debug(f"Got output: {output!r}") if "ERROR:" in output: _, error = output.split("ERROR:") diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index c75b75a68..a3aa5db96 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy -import io import logging import os import shutil @@ -492,9 +491,7 @@ class LocalFileStorage(StorageInterface): self._initialize_metadata() def _initialize_metadata(self): - self._logger.info( - "Initializing the file metadata for {}...".format(self.basefolder) - ) + self._logger.info(f"Initializing the file metadata for {self.basefolder}...") old_metadata_path = os.path.join(self.basefolder, "metadata.yaml") backup_path = os.path.join(self.basefolder, "metadata.yaml.backup") @@ -502,7 +499,7 @@ class LocalFileStorage(StorageInterface): if os.path.exists(old_metadata_path): # load the old metadata file try: - with io.open(old_metadata_path, "rt", encoding="utf-8") as f: + with open(old_metadata_path, encoding="utf-8") as f: import yaml self._old_metadata = yaml.safe_load(f) @@ -526,7 +523,7 @@ class LocalFileStorage(StorageInterface): self._list_folder(self.basefolder) self._logger.info( - "... file metadata for {} initialized successfully.".format(self.basefolder) + f"... file metadata for {self.basefolder} initialized successfully." ) @property @@ -719,7 +716,7 @@ class LocalFileStorage(StorageInterface): if not os.path.exists(source_fullpath): raise StorageError( - "{} in {} does not exist".format(source_name, source_path), + f"{source_name} in {source_path} does not exist", code=StorageError.INVALID_SOURCE, ) @@ -735,7 +732,7 @@ class LocalFileStorage(StorageInterface): and source_fullpath != destination_fullpath ): raise StorageError( - "{} does already exist in {}".format(destination_name, destination_path), + f"{destination_name} does already exist in {destination_path}", code=StorageError.INVALID_DESTINATION, ) @@ -1208,16 +1205,14 @@ class LocalFileStorage(StorageInterface): while os.path.exists(sanitized_path): counter += 1 sanitized = self.sanitize_name( - "{}_({}){}".format(sanitized_name, counter, sanitized_ext) + f"{sanitized_name}_({counter}){sanitized_ext}" ) sanitized_path = os.path.join(path, sanitized) try: shutil.move(entry_path, sanitized_path) - self._logger.info( - 'Sanitized "{}" to "{}"'.format(entry_path, sanitized_path) - ) + self._logger.info(f'Sanitized "{entry_path}" to "{sanitized_path}"') return sanitized, sanitized_path except Exception: self._logger.exception( @@ -1664,7 +1659,7 @@ class LocalFileStorage(StorageInterface): except Exception: # So something went wrong somewhere while processing this file entry - log that and continue self._logger.exception( - "Error while processing entry {}".format(entry_path) + f"Error while processing entry {entry_path}" ) continue @@ -1734,7 +1729,7 @@ class LocalFileStorage(StorageInterface): blocksize = 65536 hash = hashlib.sha1() - with io.open(path, "rb") as f: + with open(path, "rb") as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -1815,7 +1810,7 @@ class LocalFileStorage(StorageInterface): metadata = None with self._get_persisted_metadata_lock(path): if os.path.exists(metadata_path): - with io.open(metadata_path, "rt", encoding="utf-8") as f: + with open(metadata_path, encoding="utf-8") as f: try: metadata = json.load(f) except Exception: @@ -1922,7 +1917,7 @@ class LocalFileStorage(StorageInterface): ) return - with io.open(metadata_path_yaml, "rt", encoding="utf-8") as f: + with open(metadata_path_yaml, encoding="utf-8") as f: try: metadata = yaml.safe_load(f) except Exception: diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index a23f81aa9..a86e9a7f2 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -72,7 +72,7 @@ class DiskFileWrapper(AbstractFileWrapper): os.chmod(path, permissions) def stream(self): - return io.open(self.path, "rb") + return open(self.path, "rb") class StreamWrapper(AbstractFileWrapper): diff --git a/src/octoprint/logging/filters.py b/src/octoprint/logging/filters.py index fcd545ae0..9df05352e 100644 --- a/src/octoprint/logging/filters.py +++ b/src/octoprint/logging/filters.py @@ -20,7 +20,7 @@ class TornadoAccessFilter(logging.Filter): record.levelname = logging.getLevelName(record.levelno) except Exception: logging.getLogger(__name__).exception( - "Error while filtering log record {!r}".format(record) + f"Error while filtering log record {record!r}" ) return logging.Filter.filter(self, record) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 0965586ae..7d12d1ff3 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -186,7 +186,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() except Exception: logging.getLogger(__name__).exception( - "Error while retrieving preprocessors for plugin {}".format(plugin_key) + f"Error while retrieving preprocessors for plugin {plugin_key}" ) return None @@ -263,7 +263,7 @@ def call_plugin( continue if hasattr(plugin, method): - logger.debug("Calling {} on {}".format(method, plugin._identifier)) + logger.debug(f"Calling {method} on {plugin._identifier}") try: result = getattr(plugin, method)(*args, **kwargs) if callback: @@ -601,7 +601,7 @@ class PluginSettings: if item in self.deprecated_access_methods: new = self.deprecated_access_methods[item] decorator = deprecated( - "{old} has been renamed to {new}".format(old=item, new=new), + f"{item} has been renamed to {new}", stacklevel=2, ) item = new diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 9e7db9af8..71bf3218f 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -24,7 +24,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import fnmatch import inspect -import io import logging import os from collections import OrderedDict, defaultdict, namedtuple @@ -306,7 +305,7 @@ class PluginInfo: def __str__(self): if self.version: - return "{name} ({version})".format(name=self.name, version=self.version) + return f"{self.name} ({self.version})" else: return to_unicode(self.name) @@ -684,14 +683,12 @@ class PluginInfo: # we only support parsing plain text source files return result - self._logger.debug( - "Parsing plugin metadata for {} from AST of {}".format(self.key, path) - ) + self._logger.debug(f"Parsing plugin metadata for {self.key} from AST of {path}") try: import ast - with io.open(path, "rb") as f: + with open(path, "rb") as f: root = ast.parse(f.read(), filename=path) assignments = list( @@ -765,13 +762,11 @@ class PluginInfo: break except SyntaxError: - self._logger.exception( - "Invalid syntax in {} for plugin {}".format(path, self.key) - ) + self._logger.exception(f"Invalid syntax in {path} for plugin {self.key}") self.invalid_syntax = True except Exception: self._logger.exception( - "Error while parsing AST from {} for plugin {}".format(path, self.key) + f"Error while parsing AST from {path} for plugin {self.key}" ) return result @@ -1001,7 +996,7 @@ class PluginManager: module_name = None if package: - module_name = "{}.{}".format(package, key) + module_name = f"{package}.{key}" plugin = self._import_plugin_from_module( key, module_name=module_name, folder=folder, bundled=bundled @@ -1025,7 +1020,7 @@ class PluginManager: ) ) except Exception: - self.logger.exception("Error processing folder {}".format(folder)) + self.logger.exception(f"Error processing folder {folder}") return added, found @@ -1163,7 +1158,7 @@ class PluginManager: else: return None except Exception: - self.logger.exception("Could not locate plugin {key}".format(key=key)) + self.logger.exception(f"Could not locate plugin {key}") return None # Create a simple dummy entry first ... @@ -1181,14 +1176,14 @@ class PluginManager: plugin.bundled = bundled if self._is_plugin_disabled(key): - self.logger.info("Plugin {} is disabled.".format(plugin)) + self.logger.info(f"Plugin {plugin} is disabled.") plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or ( plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version) ): - self.logger.warning("Plugin {} is blacklisted.".format(plugin)) + self.logger.warning(f"Plugin {plugin} is blacklisted.") plugin.blacklisted = True python_version = get_python_version_string() @@ -1264,7 +1259,7 @@ class PluginManager: plugin.bundled = bundled except Exception: - self.logger.exception("Error loading plugin {key}".format(key=key)) + self.logger.exception(f"Error loading plugin {key}") return None if plugin.check(): @@ -1386,7 +1381,7 @@ class PluginManager: ): if plugin.blacklisted: self.logger.warning( - "Plugin {} is blacklisted. Not enabling it.".format(plugin) + f"Plugin {plugin} is blacklisted. Not enabling it." ) continue self.enable_plugin( @@ -2272,11 +2267,11 @@ def is_sub_path_of(path, parent): def is_editable_install(install_dir, package, module, location): - package_link = os.path.join(install_dir, "{}.egg-link".format(package)) + package_link = os.path.join(install_dir, f"{package}.egg-link") if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: - with io.open(package_link, "rt", encoding="utf-8") as f: + with open(package_link, encoding="utf-8") as f: contents = f.readlines() for line in contents: target = os.path.normcase( diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index 3dfb4a09b..a3e147990 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -123,7 +123,7 @@ class ActionCommandNotificationPlugin( self._notifications.append((time.time(), message)) self._plugin_manager.send_plugin_message(self._identifier, {"message": message}) - self._logger.info("Got a notification: {}".format(message)) + self._logger.info(f"Got a notification: {message}") def _clear_notifications(self): self._notifications = [] diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 4a523eb50..5e3b077e1 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -90,7 +90,7 @@ class ActionCommandPromptPlugin( and self._enable == "always" and self._enable_signal_support ): - self._printer.commands(["{command} P1".format(command=self._command)]) + self._printer.commands([f"{self._command} P1"]) elif event == Events.DISCONNECTED: self._close_prompt() @@ -130,9 +130,7 @@ class ActionCommandPromptPlugin( choice = data["choice"] if not isinstance(choice, int) or not self._prompt.validate_choice(choice): - return flask.abort( - 400, "{!r} is not a valid value for choice".format(choice) - ) + return flask.abort(400, f"{choice!r} is not a valid value for choice") self._answer_prompt(choice) @@ -208,7 +206,7 @@ class ActionCommandPromptPlugin( subcode=None, tags=None, *args, - **kwargs + **kwargs, ): if gcode != self._command: return @@ -226,7 +224,7 @@ class ActionCommandPromptPlugin( # noinspection PyProtectedMember return comm_instance._emergency_force_send( - cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode + cmd, f"Force-sending {self._command} to the printer", gcode=gcode ) # ~ capability reporting @@ -237,7 +235,7 @@ class ActionCommandPromptPlugin( if capability == self.CAP_PROMPT_SUPPORT and enabled: self._cap_prompt_support = True if self._enable == "detected" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) + self._printer.commands([f"{self._command} P1"]) # ~ prompt handling @@ -277,7 +275,7 @@ class ActionCommandPromptPlugin( self._printer.commands([self._command.format(choice=choice)], force=True) else: self._printer.commands( - ["{command} S{choice}".format(command=self._command, choice=choice)], + [f"{self._command} S{choice}"], force=True, ) diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 7aecedd1a..7eaf806c3 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import calendar -import io import os import re import sys @@ -434,9 +433,7 @@ class AnnouncementPlugin( now = time.time() if os.stat(channel_path).st_mtime + ttl > now: d = feedparser.parse(channel_path) - self._logger.debug( - "Loaded channel {} from cache at {}".format(key, channel_path) - ) + self._logger.debug(f"Loaded channel {key} from cache at {channel_path}") return d return None @@ -464,7 +461,7 @@ class AnnouncementPlugin( response = r.text channel_path = self._get_channel_cache_path(key) - with io.open(channel_path, mode="wt", encoding="utf-8") as f: + with open(channel_path, mode="wt", encoding="utf-8") as f: f.write(response) return feedparser.parse(response) @@ -518,7 +515,7 @@ class AnnouncementPlugin( """Retrieve cache path for channel key.""" safe_key = sanitize(key) - return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) + return os.path.join(self.get_plugin_data_folder(), f"{safe_key}.cache") _image_tag_re = re.compile(r"") @@ -577,7 +574,7 @@ def _lazy_images(text, placeholder=None): quote = match.group("quote") quoted_src = quote + src + quote img_tag = img_tag.replace( - match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src) + match.group(0), f'src="{placeholder}" data-src={quoted_src}' ) return img_tag @@ -602,10 +599,10 @@ def _strip_tags(text): self._fed.append(data) def handle_entityref(self, ref): - self._fed.append("&{};".format(ref)) + self._fed.append(f"&{ref};") def handle_charref(self, ref): - self._fed.append("&#{};".format(ref)) + self._fed.append(f"&#{ref};") def get_data(self): return "".join(self._fed) diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index d49bbcb3b..ca8ff3024 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -1,4 +1,3 @@ -import io import os import threading import time @@ -439,13 +438,11 @@ class AppKeysPlugin( return try: - with io.open( - self._key_path, "rt", encoding="utf-8", errors="strict" - ) as f: + with open(self._key_path, encoding="utf-8", errors="strict") as f: persisted = yaml.safe_load(f) except Exception: self._logger.exception( - "Could not load application keys from {}".format(self._key_path) + f"Could not load application keys from {self._key_path}" ) return @@ -470,7 +467,7 @@ class AppKeysPlugin( yaml.safe_dump(to_persist, f, allow_unicode=True) except Exception: self._logger.exception( - "Could not write application keys to {}".format(self._key_path) + f"Could not write application keys to {self._key_path}" ) diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 204b19648..13174e9d8 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -26,7 +26,6 @@ except ImportError: zlib = None -import io import json import logging import os @@ -506,7 +505,7 @@ class BackupPlugin( if not os.path.isdir(datafolder): os.makedirs(datafolder) - click.echo("Creating backup at {}, please wait...".format(filename)) + click.echo(f"Creating backup at {filename}, please wait...") self._create_backup( filename, exclude=exclude, @@ -550,7 +549,7 @@ class BackupPlugin( path = os.path.join(datafolder, path) if not os.path.exists(path): - click.echo("Backup {} does not exist".format(path), err=True) + click.echo(f"Backup {path} does not exist", err=True) sys.exit(-1) archive = tempfile.NamedTemporaryFile(delete=False) @@ -568,7 +567,7 @@ class BackupPlugin( pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) def log(line): - click.echo("\t{}".format(line)) + click.echo(f"\t{line}") for plugin in plugins: octoprint_compatible = is_octoprint_compatible( @@ -644,9 +643,9 @@ class BackupPlugin( on_log_error=on_log_error, on_invalid_backup=on_log_error, ): - click.echo("Restored from {}".format(path)) + click.echo(f"Restored from {path}") else: - click.echo("Restoring from {} failed".format(path), err=True) + click.echo(f"Restoring from {path} failed", err=True) return [backup_command, restore_command] @@ -725,7 +724,7 @@ class BackupPlugin( try: os.remove(full_path) except Exception: - self._logger.exception("Could not delete {}".format(filename)) + self._logger.exception(f"Could not delete {filename}") raise def _get_backups(self): @@ -754,7 +753,7 @@ class BackupPlugin( data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) if os.path.exists(data_file): try: - with io.open(data_file, mode="rt", encoding="utf-8") as f: + with open(data_file, mode="rt", encoding="utf-8") as f: unknown_plugins = json.load(f) assert isinstance(unknown_plugins, list) @@ -852,7 +851,7 @@ class BackupPlugin( r.raise_for_status() except Exception: logger.exception( - "Error while fetching the plugin repository data from {}".format(url) + f"Error while fetching the plugin repository data from {url}" ) return {} @@ -873,7 +872,7 @@ class BackupPlugin( # prepare pip caller def log(prefix, *lines): for line in lines: - on_log("{} {}".format(prefix, line.rstrip())) + on_log(f"{prefix} {line.rstrip()}") def log_call(*lines): log(">", *lines) @@ -967,7 +966,7 @@ class BackupPlugin( configfile = settings._configfile basedir = settings._basedir - temporary_path = os.path.join(datafolder, ".{}".format(name)) + temporary_path = os.path.join(datafolder, f".{name}") final_path = os.path.join(datafolder, name) own_folder = datafolder @@ -1162,7 +1161,7 @@ class BackupPlugin( temp = tempfile.mkdtemp() try: if callable(on_log_progress): - on_log_progress("Unpacking backup to {}...".format(temp)) + on_log_progress(f"Unpacking backup to {temp}...") abstemp = os.path.abspath(temp) dirs = {} @@ -1193,7 +1192,7 @@ class BackupPlugin( import yaml - with io.open(configfile, "rt", encoding="utf-8") as f: + with open(configfile, encoding="utf-8") as f: configdata = yaml.safe_load(f) userfile = os.path.join(temp, "basedir", "users.yaml") @@ -1211,7 +1210,7 @@ class BackupPlugin( plugins = [] plugin_list_file = os.path.join(temp, "plugin_list.json") if os.path.exists(plugin_list_file): - with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f: + with open(os.path.join(temp, "plugin_list.json"), "rb") as f: plugins = json.load(f) known_plugins = [] @@ -1261,16 +1260,12 @@ class BackupPlugin( basedir_extracted = os.path.join(temp, "basedir") if callable(on_log_progress): - on_log_progress( - "Renaming {} to {}...".format(basedir, basedir_backup) - ) + on_log_progress(f"Renaming {basedir} to {basedir_backup}...") shutil.move(basedir, basedir_backup) try: if callable(on_log_progress): - on_log_progress( - "Moving {} to {}...".format(basedir_extracted, basedir) - ) + on_log_progress(f"Moving {basedir_extracted} to {basedir}...") shutil.move(basedir_extracted, basedir) except Exception: if callable(on_log_error): @@ -1297,7 +1292,7 @@ class BackupPlugin( datafolder, UNKNOWN_PLUGINS_FILE ) try: - with io.open(unknown_plugins_path, mode="wb") as f: + with open(unknown_plugins_path, mode="wb") as f: f.write(to_bytes(json.dumps(unknown_plugins))) except Exception: if callable(on_log_error): @@ -1351,7 +1346,7 @@ class BackupPlugin( except Exception: if callable(on_log_error): on_log_error( - "Error while restarting via command {}".format(restart_command), + f"Error while restarting via command {restart_command}", exc_info=sys.exc_info(), ) on_log_error("Please restart OctoPrint manually") diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 043cac4af..0096f5822 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -54,9 +54,9 @@ class CoreWizardPlugin( config = { "type": "wizard", "name": name, - "template": "corewizard_{}_wizard.jinja2".format(key), - "div": "wizard_plugin_corewizard_{}".format(key), - "suffix": "_{}".format(key), + "template": f"corewizard_{key}_wizard.jinja2", + "div": f"wizard_plugin_corewizard_{key}", + "suffix": f"_{key}", } if key in additional: additional_result = additional[key]() diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 054288b80..28d0e5fab 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -228,15 +228,15 @@ class DiscoveryPlugin( name, addresses=addresses, port=port, - server="{}.local.".format(socket.gethostname()), + server=f"{socket.gethostname()}.local.", properties=txt_record, ) self._zeroconf.register_service(info, allow_name_change=True) self._zeroconf_registrations[key].append(info) - self._logger.info("Registered '{}' for {}".format(name, reg_type)) + self._logger.info(f"Registered '{name}' for {reg_type}") except Exception: self._logger.exception( - "Could not register {} for {} on port {}".format(name, reg_type, port) + f"Could not register {name} for {reg_type} on port {port}" ) def zeroconf_unregister(self, reg_type, port=None): @@ -260,10 +260,10 @@ class DiscoveryPlugin( try: for info in infos: self._zeroconf.unregister_service(info) - self._logger.debug("Unregistered {} on port {}".format(reg_type, port)) + self._logger.debug(f"Unregistered {reg_type} on port {port}") except Exception: self._logger.exception( - "Could not (fully) unregister {} on port {}".format(reg_type, port) + f"Could not (fully) unregister {reg_type} on port {port}" ) def zeroconf_browse( @@ -349,9 +349,7 @@ class DiscoveryPlugin( for address in map(lambda x: socket.inet_ntoa(x), info.addresses): result.append(to_result(info, address)) - self._logger.debug( - "Browsing Zeroconf for {service_type}".format(service_type=service_type) - ) + self._logger.debug(f"Browsing Zeroconf for {service_type}") def browse(): listener = ZeroconfListener(self._logger) @@ -706,7 +704,7 @@ class DiscoveryPlugin( + socket.inet_aton("0.0.0.0"), ) - self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) + self._logger.info(f"Registered {self.get_instance_name()} for SSDP") self._ssdp_notify(alive=True) @@ -728,7 +726,7 @@ class DiscoveryPlugin( interface_address = octoprint.util.address_for_client( *address, addresses=self._settings.get(["addresses"]), - interfaces=self._settings.get(["interfaces"]) + interfaces=self._settings.get(["interfaces"]), ) if not interface_address: continue @@ -772,9 +770,9 @@ class DiscoveryPlugin( def get_instance_name(self): name = self._settings.global_get(["appearance", "name"]) if name: - return 'OctoPrint instance "{}"'.format(name) + return f'OctoPrint instance "{name}"' else: - return "OctoPrint instance on {}".format(socket.gethostname()) + return f"OctoPrint instance on {socket.gethostname()}" def get_interface_addresses(self): addresses = self._settings.get(["addresses"]) diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index e0f367680..a27da578c 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os from os import scandir @@ -183,7 +182,7 @@ class LoggingPlugin( if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with io.open(logging_file, "rt", encoding="utf-8") as f: + with open(logging_file, encoding="utf-8") as f: config_from_file = yaml.safe_load(f) return config_from_file @@ -242,7 +241,7 @@ class LoggingPlugin( for logger, level in new_levels.items(): level = logging.getLevelName(level) - self._logger.info("Setting logger {} level to {}".format(logger, level)) + self._logger.info(f"Setting logger {logger} level to {level}") self._logger.manager.loggerDict[logger].setLevel(level) def _is_managed_logger(self, logger): diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index 63ad242ac..850d28ef2 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os import flask @@ -95,7 +94,7 @@ class ThrottleState: self._past_throttled = False for key, value in kwargs.items(): - local_key = "_{}".format(key) + local_key = f"_{key}" if hasattr(self, local_key) and isinstance(value, bool): setattr(self, local_key, value) @@ -141,7 +140,7 @@ class ThrottleState: @property def raw_value_hex(self): - return "0x{:X}".format(self._raw_value) + return f"0x{self._raw_value:X}" def __eq__(self, other): if not isinstance(other, ThrottleState): @@ -176,7 +175,7 @@ def get_proc_dt_model(): global _proc_dt_model if _proc_dt_model is None: - with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f: + with open(_PROC_DT_MODEL_PATH, encoding="utf-8") as f: _proc_dt_model = f.readline().strip(" \t\r\n\0") return _proc_dt_model @@ -189,7 +188,7 @@ def get_vcgencmd_throttled_state(command): output = sarge.get_stdout(command, close_fds=CLOSE_FDS) if "throttled=0x" not in output: - raise ValueError('cannot parse "{}" output: {}'.format(command, output)) + raise ValueError(f'cannot parse "{command}" output: {output}') value = output[len("throttled=") :].strip(" \t\r\n\0") value = int(value, 0) @@ -207,7 +206,7 @@ def get_octopi_version(): global _octopi_version if _octopi_version is None: - with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f: + with open(_OCTOPI_VERSION_PATH, encoding="utf-8") as f: _octopi_version = f.readline().strip(" \t\r\n\0") return _octopi_version @@ -362,7 +361,7 @@ class PiSupportPlugin( def _check_throttled_state(self): command = self._settings.get(["vcgencmd_throttle_check_command"]) - self._logger.debug('Retrieving throttle state via "{}"'.format(command)) + self._logger.debug(f'Retrieving throttle state via "{command}"') try: state = get_vcgencmd_throttled_state(command) except ValueError: diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 68dd969e0..375412f8d 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import copy -import io import logging import os import re @@ -705,7 +704,7 @@ class PluginManagerPlugin( kind = filetype.guess(path) if kind: - return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS + return f".{kind.extension}" in PluginManagerPlugin.ARCHIVE_EXTENSIONS return False def _is_pythonfile(self, path): @@ -714,13 +713,11 @@ class PluginManagerPlugin( import ast try: - with io.open(path, "rb") as f: + with open(path, "rb") as f: ast.parse(f.read(), filename=path) return True except Exception as exc: - self._logger.exception( - "Could not parse {} as python file: {}".format(path, exc) - ) + self._logger.exception(f"Could not parse {path} as python file: {exc}") return False @@ -767,12 +764,12 @@ class PluginManagerPlugin( raise exceptions.InvalidPackageFormat() except requests.exceptions.HTTPError as e: - self._logger.error("Could not fetch plugin from server, got {}".format(e)) + self._logger.error(f"Could not fetch plugin from server, got {e}") result = { "result": False, "source": source, "source_type": source_type, - "reason": "Could not fetch plugin from server, got {}".format(e), + "reason": f"Could not fetch plugin from server, got {e}", } self._send_result_notification("install", result) @@ -863,7 +860,7 @@ class PluginManagerPlugin( lambda line: path_url in line.lower() ) # lower case in case of windows - self._logger.info("Installing plugin from {}".format(source)) + self._logger.info(f"Installing plugin from {source}") pip_args = [ "--disable-pip-version-check", "install", @@ -909,7 +906,7 @@ class PluginManagerPlugin( ) force = True except Exception as e: - self._logger.exception("Could not install plugin from {}".format(source)) + self._logger.exception(f"Could not install plugin from {source}") self._logger.exception("Reason: {}".format(repr(e))) result = { "result": False, @@ -930,9 +927,7 @@ class PluginManagerPlugin( try: returncode, stdout, stderr = self._call_pip(pip_args) except Exception as e: - self._logger.exception( - "Could not install plugin from {}".format(source) - ) + self._logger.exception(f"Could not install plugin from {source}") self._logger.exception("Reason: {}".format(repr(e))) result = { "result": False, @@ -1092,7 +1087,7 @@ class PluginManagerPlugin( if name is None: name = os.path.basename(path) - self._logger.info("Installing single file plugin {} from {}".format(name, source)) + self._logger.info(f"Installing single file plugin {name} from {source}") all_plugins_before = self._plugin_manager.find_plugins(existing={}) @@ -1100,10 +1095,10 @@ class PluginManagerPlugin( plugin_id, _ = os.path.splitext(name) try: - self._log_call("cp {} {}".format(path, destination)) + self._log_call(f"cp {path} {destination}") shutil.copy(path, destination) except Exception: - self._logger.exception("Installing plugin from {} failed".format(source)) + self._logger.exception(f"Installing plugin from {source} failed") result = { "result": False, "source": source, @@ -1221,22 +1216,16 @@ class PluginManagerPlugin( if os.path.isdir(full_path): # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout( - "Deleting plugin from {folder}".format(folder=plugin.location) - ) + self._log_stdout(f"Deleting plugin from {plugin.location}") shutil.rmtree(full_path) elif os.path.isfile(full_path): - self._log_stdout( - "Deleting plugin from {file}".format(file=plugin.location) - ) + self._log_stdout(f"Deleting plugin from {plugin.location}") os.remove(full_path) if full_path.endswith(".py"): pyc_file = "{full_path}c".format(**locals()) if os.path.isfile(pyc_file): - self._log_stdout( - "Deleting plugin from {file}".format(file=pyc_file) - ) + self._log_stdout(f"Deleting plugin from {pyc_file}") os.remove(pyc_file) else: @@ -1270,9 +1259,7 @@ class PluginManagerPlugin( if plugin.enabled: self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception( - "Problem disabling plugin {name}".format(name=plugin.key) - ) + self._logger.exception(f"Problem disabling plugin {plugin.key}") result = { "result": False, "uninstalled": True, @@ -1287,9 +1274,7 @@ class PluginManagerPlugin( if plugin.loaded: self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception( - "Problem unloading plugin {name}".format(name=plugin.key) - ) + self._logger.exception(f"Problem unloading plugin {plugin.key}") result = { "result": False, "uninstalled": True, @@ -1316,7 +1301,7 @@ class PluginManagerPlugin( "plugin": self._to_external_plugin(plugin), } self._send_result_notification("uninstall", result) - self._logger.info("Plugin {} uninstalled".format(plugin.key)) + self._logger.info(f"Plugin {plugin.key} uninstalled") self._cleanup_disabled(plugin.key) if cleanup: @@ -1337,7 +1322,7 @@ class PluginManagerPlugin( key = plugin.key result_value = self._to_external_plugin(plugin) - message = "Cleaning up plugin {}...".format(key) + message = f"Cleaning up plugin {key}..." self._logger.info(message) self._log_stdout(message) @@ -1351,7 +1336,7 @@ class PluginManagerPlugin( # delete plugin data folder result_data = True if not self._cleanup_data(key): - message = "Could not delete data folder of plugin {}".format(key) + message = f"Could not delete data folder of plugin {key}" self._logger.exception(message) self._log_stderr(message) result_data = False @@ -1425,7 +1410,7 @@ class PluginManagerPlugin( return True except Exception: self._logger.exception( - "Could not delete plugin data folder at {}".format(data_folder) + f"Could not delete plugin data folder at {data_folder}" ) return False else: @@ -1679,9 +1664,7 @@ class PluginManagerPlugin( try: import json - with io.open( - self._repository_cache_path, "rt", encoding="utf-8" - ) as f: + with open(self._repository_cache_path, encoding="utf-8") as f: repo_data = json.load(f) self._repository_mtime = mtime self._logger.info( @@ -1707,9 +1690,7 @@ class PluginManagerPlugin( try: r = requests.get(repository_url, timeout=30) r.raise_for_status() - self._logger.info( - "Loaded plugin repository data from {}".format(repository_url) - ) + self._logger.info(f"Loaded plugin repository data from {repository_url}") except Exception as e: self._logger.exception( "Could not fetch plugins from repository at {repository_url}: {message}".format( @@ -1721,13 +1702,13 @@ class PluginManagerPlugin( try: repo_data = r.json() except Exception as e: - self._logger.exception("Error while reading repository data: {}".format(e)) + self._logger.exception(f"Error while reading repository data: {e}") return None # validation if not isinstance(repo_data, (list, tuple)): self._logger.warning( - "Invalid repository data: expected a list, got {!r}".format(repo_data) + f"Invalid repository data: expected a list, got {repo_data!r}" ) return None @@ -1774,7 +1755,7 @@ class PluginManagerPlugin( try: import json - with io.open(self._notices_cache_path, "rt", encoding="utf-8") as f: + with open(self._notices_cache_path, encoding="utf-8") as f: notice_data = json.load(f) self._notices_mtime = mtime self._logger.info("Loaded notice data from disk, was still valid") @@ -1798,7 +1779,7 @@ class PluginManagerPlugin( try: r = requests.get(notices_url, timeout=30) r.raise_for_status() - self._logger.info("Loaded plugin notices data from {}".format(notices_url)) + self._logger.info(f"Loaded plugin notices data from {notices_url}") except Exception as e: self._logger.exception( "Could not fetch notices from {notices_url}: {message}".format( diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index a30f161ff..f821fa89f 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -5,7 +5,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy import hashlib -import io import logging import logging.handlers import os @@ -334,9 +333,7 @@ class SoftwareUpdatePlugin( data = psutil.disk_usage(path) info["free"] = data.free except Exception: - self._logger.exception( - "Error while determining disk usage of {}".format(path) - ) + self._logger.exception(f"Error while determining disk usage of {path}") continue storage_info[key] = info @@ -372,15 +369,13 @@ class SoftwareUpdatePlugin( ) def _get_check_overlay(self, url): - self._logger.info("Fetching check overlays from {}".format(url)) + self._logger.info(f"Fetching check overlays from {url}") try: r = requests.get(url, timeout=3.1) r.raise_for_status() data = r.json() except Exception as exc: - self._logger.error( - "Could not fetch check overlay from {}: {}".format(url, exc) - ) + self._logger.error(f"Could not fetch check overlay from {url}: {exc}") return {} else: return data @@ -426,7 +421,7 @@ class SoftwareUpdatePlugin( import yaml try: - with io.open(self._version_cache_path, "rt", encoding="utf-8") as f: + with open(self._version_cache_path, encoding="utf-8") as f: data = yaml.safe_load(f) timestamp = os.stat(self._version_cache_path).st_mtime except Exception: @@ -1140,9 +1135,7 @@ class SoftwareUpdatePlugin( try: populated_check = self._populated_check(target, checks[target]) except exceptions.UnknownCheckType: - self._logger.debug( - "Ignoring unknown check type for target {}".format(target) - ) + self._logger.debug(f"Ignoring unknown check type for target {target}") continue except Exception: self._logger.exception( @@ -1310,7 +1303,7 @@ class SoftwareUpdatePlugin( continue except Exception: self._logger.exception( - "Could not check {} for updates".format(target) + f"Could not check {target} for updates" ) continue @@ -1461,7 +1454,7 @@ class SoftwareUpdatePlugin( if isinstance(value, dict): lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value))) else: - lines.append("{!r}: {!r}".format(key, value)) + lines.append(f"{key!r}: {value!r}") return "{" + ", ".join(lines) + "}" @@ -1538,7 +1531,7 @@ class SoftwareUpdatePlugin( error = "unknown_check" except exceptions.NetworkError: self._logger.warning( - "Could not check {} for updates due to a network error".format(target) + f"Could not check {target} for updates due to a network error" ) update_possible = False error = "network" @@ -1552,12 +1545,12 @@ class SoftwareUpdatePlugin( error = "ratelimit" except exceptions.CheckError: self._logger.warning( - "Could not check {} for updates due to a check error".format(target) + f"Could not check {target} for updates due to a check error" ) update_possible = False error = "check" except Exception: - self._logger.exception("Could not check {} for updates".format(target)) + self._logger.exception(f"Could not check {target} for updates") update_possible = False error = "unknown" else: @@ -1567,9 +1560,7 @@ class SoftwareUpdatePlugin( target, check, online=online ) except Exception: - self._logger.exception( - "Error while checking if {} can be updated".format(target) - ) + self._logger.exception(f"Error while checking if {target} can be updated") update_possible = False self._version_cache[target] = { @@ -1609,9 +1600,7 @@ class SoftwareUpdatePlugin( try: populated_checks[target] = self._populated_check(target, check) except exceptions.UnknownCheckType: - self._logger.debug( - "Ignoring unknown check type for target {}".format(target) - ) + self._logger.debug(f"Ignoring unknown check type for target {target}") except Exception: self._logger.exception( "Error while populating check prior to update for target {}".format( @@ -1800,9 +1789,7 @@ class SoftwareUpdatePlugin( populated_check = self._populated_check(target, check) try: - self._logger.info( - "Starting update of {} to {}...".format(target, target_version) - ) + self._logger.info(f"Starting update of {target} to {target_version}...") self._send_client_message( "updating", { @@ -1819,9 +1806,7 @@ class SoftwareUpdatePlugin( target, populated_check, target_version, log_cb=self._log, online=online ) target_result = ("success", update_result) - self._logger.info( - "Update of {} to {} successful!".format(target, target_version) - ) + self._logger.info(f"Update of {target} to {target_version} successful!") trigger_event(True) except exceptions.UnknownUpdateType: @@ -1926,10 +1911,10 @@ class SoftwareUpdatePlugin( util.execute(restart_command, evaluate_returncode=False, do_async=True) except exceptions.ScriptError as e: self._logger.exception( - "Error while restarting via command {}".format(restart_command) + f"Error while restarting via command {restart_command}" ) - self._logger.warning("Restart stdout:\n{}".format(e.stdout)) - self._logger.warning("Restart stderr:\n{}".format(e.stderr)) + self._logger.warning(f"Restart stdout:\n{e.stdout}") + self._logger.warning(f"Restart stderr:\n{e.stderr}") raise exceptions.RestartFailed() def _populated_check(self, target, check): @@ -2067,7 +2052,7 @@ class SoftwareUpdatePlugin( data={"loglines": [{"line": line, "stream": stream} for line in lines]}, ) for line in lines: - self._console_logger.debug("{} {}".format(prefix, line)) + self._console_logger.debug(f"{prefix} {line}") def _send_client_message(self, message_type, data=None): self._plugin_manager.send_plugin_message( diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 0c9b2c0f4..4590f0b96 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -62,7 +62,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): try: r.raise_for_status() except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) + click.echo(f"Could not get update information from server, got {e}") sys.exit(1) data = r.json() @@ -230,7 +230,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): try: r.raise_for_status() except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) + click.echo(f"Could not get update information from server, got {e}") sys.exit(1) data = r.json() diff --git a/src/octoprint/plugins/softwareupdate/exceptions.py b/src/octoprint/plugins/softwareupdate/exceptions.py index 6d6d0d892..93fb909b7 100644 --- a/src/octoprint/plugins/softwareupdate/exceptions.py +++ b/src/octoprint/plugins/softwareupdate/exceptions.py @@ -29,7 +29,7 @@ class NetworkError(Exception): if self.message is not None: return self.message elif self.cause is not None: - return "NetworkError caused by {}".format(self.cause) + return f"NetworkError caused by {self.cause}" else: return "NetworkError" diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 9f03044cd..0a9873553 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -91,14 +91,12 @@ def _execute(command, **kwargs): if not p.commands[0].process: # the process might have been set to None in case of any exception print( - "Error while trying to run command {}".format(joined_command), + f"Error while trying to run command {joined_command}", file=sys.stderr, ) return None, [], [] except Exception: - print( - "Error while trying to run command {}".format(joined_command), file=sys.stderr - ) + print(f"Error while trying to run command {joined_command}", file=sys.stderr) traceback.print_exc(file=sys.stderr) return None, [], [] @@ -214,7 +212,7 @@ def _rescue_changes(git_executable, folder): ) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git diff" failed with returncode {}'.format(returncode) + f'Could not update, "git diff" failed with returncode {returncode}' ) if stdout and "".join(stdout).strip(): # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch @@ -222,9 +220,9 @@ def _rescue_changes(git_executable, folder): import time timestamp = time.strftime("%Y%m%d%H%M") - patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp)) + patch = os.path.join(folder, f"{timestamp}-preupdate.patch") - print(">>> Running: git diff and saving output to {}".format(patch)) + print(f">>> Running: git diff and saving output to {patch}") returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( @@ -233,9 +231,7 @@ def _rescue_changes(git_executable, folder): ) ) - import io - - with io.open(patch, "wt", encoding="utf-8", errors="replace") as f: + with open(patch, "wt", encoding="utf-8", errors="replace") as f: for line in stdout: f.write(line) @@ -274,11 +270,11 @@ def update_source(git_executable, folder, target, force=False, branch=None): returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git fetch" failed with returncode {}'.format(returncode) + f'Could not update, "git fetch" failed with returncode {returncode}' ) if branch is not None and branch.strip() != "": - print(">>> Running: git checkout {}".format(branch)) + print(f">>> Running: git checkout {branch}") returncode, stdout, stderr = _git( ["checkout", branch], folder, git_executable=git_executable ) @@ -293,7 +289,7 @@ def update_source(git_executable, folder, target, force=False, branch=None): returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git pull" failed with returncode {}'.format(returncode) + f'Could not update, "git pull" failed with returncode {returncode}' ) if force: @@ -316,7 +312,7 @@ def install_source(python_executable, folder, user=False, sudo=False): print(">>> Running: python setup.py clean") returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable) if returncode is None or returncode != 0: - print('"python setup.py clean" failed with returncode {}'.format(returncode)) + print(f'"python setup.py clean" failed with returncode {returncode}') print("Continuing anyways") print(">>> Running: python setup.py install") @@ -407,7 +403,7 @@ def main(): if python_executable.endswith('"'): python_executable = python_executable[:-1] - print("Python executable: {!r}".format(python_executable)) + print(f"Python executable: {python_executable!r}") folder = args.folder diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index e10e15131..b1dfbcdcb 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -98,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc target_version=target_version, target=target_version ) - logger.debug("Target: {}, executing pip install {}".format(target, install_arg)) + logger.debug(f"Target: {target}, executing pip install {install_arg}") pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] pip_kwargs = { "env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"} diff --git a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py index 9e39ea6c5..6af58a171 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py +++ b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py @@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License" import ast -import io import logging import os import shutil @@ -46,7 +45,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc folder = None try: try: - _log_message("Download file from {}".format(url)) + _log_message(f"Download file from {url}") folder = TemporaryDirectory() path = download_file(url, folder.name) except Exception as exc: @@ -55,29 +54,25 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc filename = os.path.basename(path) _, ext = os.path.splitext(filename) if ext not in (".py",): - raise exceptions.UpdateError( - "File is not a python file: {}".format(filename), None - ) + raise exceptions.UpdateError(f"File is not a python file: {filename}", None) try: - with io.open(path, "rb") as f: + with open(path, "rb") as f: ast.parse(f.read(), filename=path) except Exception: - logger.exception("Could not parse {} as python file".format(path), None) + logger.exception(f"Could not parse {path} as python file", None) raise exceptions.UpdateError( - "Could not parse {} as python file.".format(filename), None + f"Could not parse {filename} as python file.", None ) destination = os.path.join(settings().getBaseFolder("plugins"), filename) try: - _log_message("Copy {} to {}".format(path, destination)) + _log_message(f"Copy {path} to {destination}") shutil.copy(path, destination) except Exception: - logger.exception("Could not copy {} to {}".format(path, destination)) - raise exceptions.UpdateError( - "Could not copy {} to {}".format(path, destination), None - ) + logger.exception(f"Could not copy {path} to {destination}") + raise exceptions.UpdateError(f"Could not copy {path} to {destination}", None) return "ok" finally: diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py index 2bf31153f..d0b1ee44c 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -78,9 +78,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True): ### pre update if pre_update_script is not None: - logger.debug( - "Target: {}, running pre-update script: {}".format(target, pre_update_script) - ) + logger.debug(f"Target: {target}, running pre-update script: {pre_update_script}") try: caller.checked_call(pre_update_script, cwd=folder) except CommandlineError as e: @@ -100,9 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True): force="true" if force_exact_version else "false", ) - logger.debug( - "Target {}, running update script: {}".format(target, update_command) - ) + logger.debug(f"Target {target}, running update script: {update_command}") caller.checked_call(update_command, cwd=folder) except CommandlineError as e: diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index 69f83dcc2..f9b2a2922 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -27,9 +27,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs): async_=do_async, ) except Exception: - logging.getLogger(__name__).exception( - "Error while executing command: {}".format(command) - ) + logging.getLogger(__name__).exception(f"Error while executing command: {command}") returncode = p.returncode if p is not None else None stdout = p.stdout.text if p is not None and p.stdout is not None else "" stderr = p.stderr.text if p is not None and p.stderr is not None else "" diff --git a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py index b831968d5..737fbe3ce 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py @@ -21,7 +21,7 @@ from . import ( # noqa: F401 class GithubRateLimitCheckError(RateLimitCheckError): def __init__(self, remaining, ratelimit, reset): if reset: - message = "Github rate limit exceeded, reset at {}".format(reset) + message = f"Github rate limit exceeded, reset at {reset}" else: message = "Github rate limit exceeded" super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset) diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index 66c298426..45a51d824 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -24,7 +24,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): auth_value = base64.b64encode( b"{user}:{pw}".format(user=api_user, pw=api_password) ) - headers["authorization"] = "Basic {}".format(auth_value) + headers["authorization"] = f"Basic {auth_value}" try: r = requests.get(url, headers=headers, timeout=(3.05, 30)) @@ -79,19 +79,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): remote_commit = _get_latest_commit( check["user"], check["repo"], branch, api_user, api_password ) - remote_name = ( - "Commit {commit}".format(commit=remote_commit) - if remote_commit is not None - else "-" - ) + remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-" information["remote"] = {"name": remote_name, "value": remote_commit} is_current = ( current is not None and current == remote_commit ) or remote_commit is None - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) - ) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py index c5f226018..42ec5d963 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py @@ -56,8 +56,6 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.github_commit" ) - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, local_name, remote_name) - ) + logger.debug(f"Target: {target}, local: {local_name}, remote: {remote_name}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py index 96ab26569..1fa0e3591 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py @@ -97,8 +97,6 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.git_commit" ) - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit) - ) + logger.debug(f"Target: {target}, local: {local_commit}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py index 56187b0fe..551dd7d69 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -83,19 +83,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): remote_commit = _get_latest_commit( check["user"], check["repo"], branch, apikey=apikey ) - remote_name = ( - "Commit {commit}".format(commit=remote_commit) - if remote_commit is not None - else "-" - ) + remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-" information["remote"] = {"name": remote_name, "value": remote_commit} is_current = ( current is not None and current == remote_commit ) or remote_commit is None - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) - ) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py index 19690a3c4..c755bf639 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -198,7 +198,7 @@ def _get_comparable_version_semantic(version_string, force_base=True): version = semantic_version.Version.coerce(version_string, partial=False) if force_base: - version_string = "{}.{}.{}".format(version.major, version.minor, version.patch) + version_string = f"{version.major}.{version.minor}.{version.patch}" version = semantic_version.Version.coerce(version_string, partial=False) return version @@ -355,7 +355,7 @@ def get_latest( "release_notes": release_notes, } - logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag)) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_tag}") return information, _is_current( information, compare_type, custom=custom_compare, force_base=force_base diff --git a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py index ce8232e63..0d1d48107 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py @@ -26,7 +26,7 @@ def get_latest(target, check, online=True, *args, **kwargs): method = check.get("header_method", "head") prefix = check.get("header_prefix", header) if prefix: - prefix = "{} ".format(prefix) + prefix = f"{prefix} " try: with requests.request(method, url) as r: diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 1119ef04f..20cf99e52 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -479,7 +479,7 @@ class TrackingPlugin( # Don't print the URL or UUID! That would expose the UUID in forums/tickets # if pasted. It's okay for the user to know their uuid, but it shouldn't be shared. - headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + headers = {"User-Agent": f"OctoPrint/{get_octoprint_version_string()}"} try: params = urlencode(kwargs, doseq=True).replace("+", "%20") @@ -488,9 +488,7 @@ class TrackingPlugin( else: requests.get(url, params=params, timeout=3.1, headers=headers) - self._logger.info( - "Sent tracking event {}, payload: {!r}".format(event, kwargs) - ) + self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}") except Exception: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 756a79656..8ab167149 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -3,7 +3,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp import collections -import io import json import math import os @@ -300,7 +299,7 @@ class VirtualPrinter: @timeout.setter def timeout(self, value): - self._logger.debug("Setting read timeout to {}s".format(value)) + self._logger.debug(f"Setting read timeout to {value}s") self._read_timeout = value @property @@ -309,7 +308,7 @@ class VirtualPrinter: @write_timeout.setter def write_timeout(self, value): - self._logger.debug("Setting write timeout to {}s".format(value)) + self._logger.debug(f"Setting write timeout to {value}s") self._write_timeout = value @property @@ -493,7 +492,7 @@ class VirtualPrinter: try: # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first - letter_handler = "_gcode_{}".format(letter) + letter_handler = f"_gcode_{letter}" if hasattr(self, letter_handler): code = command_match.group(2) handled = getattr(self, letter_handler)(code, data) @@ -501,7 +500,7 @@ class VirtualPrinter: continue # then look for a method _gcode_ and execute that if it exists - command_handler = "_gcode_{}".format(command) + command_handler = f"_gcode_{command}" if hasattr(self, command_handler): handled = getattr(self, command_handler)(data) if handled: @@ -541,7 +540,7 @@ class VirtualPrinter: self.currentExtruder = t self._send("Active Extruder: %d" % self.currentExtruder) else: - self._send("echo:T{} Invalid extruder ".format(t)) + self._send(f"echo:T{t} Invalid extruder ") # noinspection PyUnusedLocal def _gcode_F(self, code, data): @@ -685,7 +684,7 @@ class VirtualPrinter: if not self._okBeforeCommandOutput: ok = self._ok() if ok: - output = "{} {}".format(self._ok(), output) + output = f"{self._ok()} {output}" self._send(output) return True @@ -1233,7 +1232,7 @@ class VirtualPrinter: | Unsets the busy loop. """ for line in usage.split("\n"): - self._send("echo: {}".format(line.strip())) + self._send(f"echo: {line.strip()}") elif data == "action_pause": self._send("// action:pause") elif data == "action_resume": @@ -1303,9 +1302,7 @@ class VirtualPrinter: if sleep_match is not None: interval = int(sleep_match.group(1)) - self._send( - "// sleeping for {interval} seconds".format(interval=interval) - ) + self._send(f"// sleeping for {interval} seconds") self._debug_sleep = interval elif sleep_after_match is not None: command = sleep_after_match.group(1) @@ -1460,7 +1457,7 @@ class VirtualPrinter: ["smoothieTemperatureReporting"] ): continue - temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i]) + temps[f"T{i}"] = (self.temp[i], self.targetTemp[i]) if self._settings.get_boolean(["hasBed"]): temps["B"] = (self.bedTemp, self.bedTargetTemp) @@ -1497,7 +1494,7 @@ class VirtualPrinter: if includeOk: ok = self._ok() if ok: - output = "{} {}".format(ok, output) + output = f"{ok} {output}" self._send(output) def _parseHotendCommand( @@ -1739,7 +1736,7 @@ class VirtualPrinter: handle = None try: - handle = io.open(file, "wt", encoding="utf-8") + handle = open(file, "wt", encoding="utf-8") except Exception: self._send("error writing to file") self._writingToSdHandle = handle @@ -1761,7 +1758,7 @@ class VirtualPrinter: def _sdPrintingWorker(self): self._selectedSdFilePos = 0 try: - with io.open(self._selectedSdFile, "rt", encoding="utf-8") as f: + with open(self._selectedSdFile, encoding="utf-8") as f: for line in iter(f.readline, ""): if self._killed or not self._sdPrinting: break @@ -1922,7 +1919,7 @@ class VirtualPrinter: def loop(): while self._busy: - self._send("echo:busy {}".format(self._busy)) + self._send(f"echo:busy {self._busy}") time.sleep(self._busyInterval) self._sendOk() @@ -1936,9 +1933,9 @@ class VirtualPrinter: def _showPrompt(self, text, choices): self._hidePrompt() - self._send("//action:prompt_begin {}".format(text)) + self._send(f"//action:prompt_begin {text}") for choice in choices: - self._send("//action:prompt_button {}".format(choice)) + self._send(f"//action:prompt_button {choice}") self._send("//action:prompt_show") def _hidePrompt(self): @@ -1962,7 +1959,7 @@ class VirtualPrinter: return 0 if b"M112" in data and self._supportM112: - self._seriallog.info("<<< {}".format(u_data)) + self._seriallog.info(f"<<< {u_data}") self._kill() return len(data) @@ -1970,7 +1967,7 @@ class VirtualPrinter: written = self.incoming.put( data, timeout=self._write_timeout, partial=True ) - self._seriallog.info("<<< {}".format(u_data)) + self._seriallog.info(f"<<< {u_data}") return written except queue.Full: self._logger.info( @@ -2008,7 +2005,7 @@ class VirtualPrinter: try: # fetch a line from the queue, wait no longer than timeout line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace") - self._seriallog.info(">>> {}".format(line.strip())) + self._seriallog.info(f">>> {line.strip()}") self.outgoing.task_done() return to_bytes(line) except queue.Empty: @@ -2062,13 +2059,13 @@ class VirtualEEPROM: def _initialise_eeprom(self): if os.path.exists(self._eeprom_file_path): # file exists, read it - with io.open(self._eeprom_file_path, "rt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, encoding="utf-8") as eeprom_file: data = json.load(eeprom_file) return data else: # no eeprom file, make new one with defaults data = self.get_default_settings() - with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: eeprom_file.write(to_unicode(json.dumps(data))) return data @@ -2179,7 +2176,7 @@ class VirtualEEPROM: def save_settings(self): # M500 behind-the-scenes - with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: eeprom_file.write(to_unicode(json.dumps(self._eeprom))) def read_settings(self): @@ -2187,7 +2184,7 @@ class VirtualEEPROM: if not os.path.exists(self._eeprom_file_path): self.load_defaults() self.save_settings() - with io.open(self._eeprom_file_path, "rt") as eeprom_file: + with open(self._eeprom_file_path) as eeprom_file: self._eeprom = json.load(eeprom_file) def load_defaults(self): diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index cd7d44831..2d16336f9 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -145,7 +145,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy -import io import logging import os from os import scandir @@ -475,7 +474,7 @@ class PrinterProfileManager: try: profile = self._load_from_path(path) except InvalidProfileError: - self._logger.warning("Profile {} is invalid, skipping".format(identifier)) + self._logger.warning(f"Profile {identifier} is invalid, skipping") continue if profile is None: @@ -503,7 +502,7 @@ class PrinterProfileManager: import yaml - with io.open(path, "rt", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: profile = yaml.safe_load(f) if profile is None or not isinstance(profile, dict): diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index ffea6cc7a..8adc36a53 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -44,7 +44,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): from collections import deque self._logger = logging.getLogger(__name__) - self._logger_job = logging.getLogger("{}.job".format(__name__)) + self._logger_job = logging.getLogger(f"{__name__}.job") self._dict = ( frozendict @@ -104,13 +104,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): try: estimator = hook() if estimator is not None: - self._logger.info( - "Using print time estimator provided by {}".format(name) - ) + self._logger.info(f"Using print time estimator provided by {name}") self._estimator_factory = estimator except Exception: self._logger.exception( - "Error while processing analysis queues from {}".format(name), + f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) @@ -277,7 +275,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): plugin_data[name] = additional except ValueError: self._logger.exception( - "Invalid additional data from plugin {}".format(name), + f"Invalid additional data from plugin {name}", extra={"plugin": name}, ) except Exception: @@ -444,7 +442,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): # this code preserves existing CamelCase event_name = name[0].upper() + name[1:] - event_start = "GcodeScript{}Running".format(event_name) + event_start = f"GcodeScript{event_name}Running" payload = context.get("event", None) if isinstance(context, dict) else None eventManager().fire(event_start, payload) @@ -458,7 +456,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if not result and must_be_set: raise UnknownScript(name) - event_end = "GcodeScript{}Finished".format(event_name) + event_end = f"GcodeScript{event_name}Finished" eventManager().fire(event_end, payload) def jog(self, axes, relative=True, speed=None, *args, **kwargs): @@ -470,9 +468,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): raise ValueError("amount not set") amount = args[0] if not isinstance(amount, (int, float)): - raise ValueError( - "amount must be a valid number: {amount}".format(amount=amount) - ) + raise ValueError(f"amount must be a valid number: {amount}") axes = {} axes[axis] = amount @@ -489,7 +485,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) command = "G1 {}".format( - " ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()]) + " ".join([f"{axis.upper()}{amt}" for axis, amt in axes.items()]) ) if speed is None: @@ -497,7 +493,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): speed = min([printer_profile["axes"][axis]["speed"] for axis in axes]) if speed and not isinstance(speed, bool): - command += " F{}".format(speed) + command += f" F{speed}" if relative: commands = ["G91", command, "G90"] @@ -511,9 +507,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if isinstance(axes, str): axes = [axes] else: - raise ValueError( - "axes is neither a list nor a string: {axes}".format(axes=axes) - ) + raise ValueError(f"axes is neither a list nor a string: {axes}") validated_axes = list( filter( @@ -521,7 +515,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) ) if len(axes) != len(validated_axes): - raise ValueError("axes contains invalid axes: {axes}".format(axes=axes)) + raise ValueError(f"axes contains invalid axes: {axes}") self.commands( [ @@ -534,9 +528,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def extrude(self, amount, speed=None, *args, **kwargs): if not isinstance(amount, (int, float)): - raise ValueError( - "amount must be a valid number: {amount}".format(amount=amount) - ) + raise ValueError(f"amount must be a valid number: {amount}") printer_profile = self._printerProfileManager.get_current_or_default() @@ -557,7 +549,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def change_tool(self, tool, *args, **kwargs): if not PrinterInterface.valid_tool_regex.match(tool): - raise ValueError('tool must match "tool[0-9]+": {tool}'.format(tool=tool)) + raise ValueError(f'tool must match "tool[0-9]+": {tool}') tool_num = int(tool[len("tool") :]) self.commands( @@ -574,9 +566,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) if not isinstance(value, (int, float)) or value < 0: - raise ValueError( - "value must be a valid number >= 0: {value}".format(value=value) - ) + raise ValueError(f"value must be a valid number >= 0: {value}") tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"} @@ -586,15 +576,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): shared_nozzle = printer_profile["extruder"]["sharedNozzle"] if extruder_count > 1 and not shared_nozzle: toolNum = int(heater[len("tool") :]) - self.commands("M104 T{} S{}".format(toolNum, value), tags=tags) + self.commands(f"M104 T{toolNum} S{value}", tags=tags) else: - self.commands("M104 S{}".format(value), tags=tags) + self.commands(f"M104 S{value}", tags=tags) elif heater == "bed": - self.commands("M140 S{}".format(value), tags=tags) + self.commands(f"M140 S{value}", tags=tags) elif heater == "chamber": - self.commands("M141 S{}".format(value), tags=tags) + self.commands(f"M141 S{value}", tags=tags) def set_temperature_offset(self, offsets=None, *args, **kwargs): if offsets is None: @@ -611,13 +601,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) if len(validated_keys) != len(offsets): - raise ValueError( - "offsets contains invalid keys: {offsets}".format(offsets=offsets) - ) + raise ValueError(f"offsets contains invalid keys: {offsets}") if len(validated_values) != len(offsets): - raise ValueError( - "offsets contains invalid values: {offsets}".format(offsets=offsets) - ) + raise ValueError(f"offsets contains invalid values: {offsets}") if self._comm is None: return @@ -633,9 +619,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): factor = int(factor * 100) if min_val and factor < min_val: - raise ValueError("factor must be a value >={}".format(min_val)) + raise ValueError(f"factor must be a value >={min_val}") elif max_val and factor > max_val: - raise ValueError("factor must be a value <={}".format(max_val)) + raise ValueError(f"factor must be a value <={max_val}") return factor @@ -973,7 +959,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): sd_upload_succeeded, sd_upload_failed, *args, - **kwargs + **kwargs, ) if result is not None: return result @@ -1163,7 +1149,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) except Exception: self._logger.exception( - "Error while estimating print time via {}".format(estimator) + f"Error while estimating print time via {estimator}" ) return self._dict( @@ -1212,9 +1198,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def _validateJob(self, filename, sd): if not valid_file_type(filename, type="machinecode"): - raise InvalidFileType( - "{} is not a machinecode file, cannot print".format(filename) - ) + raise InvalidFileType(f"{filename} is not a machinecode file, cannot print") if sd: return diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 9d1d2eadf..534c28e91 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import atexit import base64 -import io import logging import logging.config import mimetypes @@ -393,7 +392,7 @@ class Server: analysis_queue_factories.update(**additional_factories) except Exception: self._logger.exception( - "Error while processing analysis queues from {}".format(name), + f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) analysisQueue = octoprint.filemanager.analysis.AnalysisQueue( @@ -497,7 +496,7 @@ class Server: groupManager = factory(components, self._settings) if groupManager is not None: self._logger.debug( - "Created group manager instance from factory {}".format(name) + f"Created group manager instance from factory {name}" ) break except Exception: @@ -531,7 +530,7 @@ class Server: userManager = factory(components, self._settings) if userManager is not None: self._logger.debug( - "Created user manager instance from factory {}".format(name) + f"Created user manager instance from factory {name}" ) break except Exception: @@ -562,13 +561,11 @@ class Server: try: printer = factory(components) if printer is not None: - self._logger.debug( - "Created printer instance from factory {}".format(name) - ) + self._logger.debug(f"Created printer instance from factory {name}") break except Exception: self._logger.exception( - "Error while creating printer instance from factory {}".format(name), + f"Error while creating printer instance from factory {name}", extra={"plugin": name}, ) else: @@ -1095,7 +1092,7 @@ class Server: connectionOptions = printer.__class__.get_connection_options() if port in connectionOptions["ports"] or port == "AUTO" or port is None: self._logger.info( - "Trying to connect to configured serial port {}".format(port) + f"Trying to connect to configured serial port {port}" ) printer.connect( port=port, @@ -1152,9 +1149,7 @@ class Server: if self._host == "::": if self._v6_only: # only v6 - self._logger.info( - "Listening on http://[::]:{port}".format(port=self._port) - ) + self._logger.info(f"Listening on http://[::]:{self._port}") else: # all v4 and v6 self._logger.info( @@ -1327,7 +1322,7 @@ class Server: logger.info("Server heartbeat <3") interval = settings().getFloat(["server", "heartbeat"]) - logger.info("Starting server heartbeat, {}s interval".format(interval)) + logger.info(f"Starting server heartbeat, {interval}s interval") timer = octoprint.util.RepeatedTimer(interval, log_heartbeat) timer.start() @@ -1427,7 +1422,7 @@ class Server: result.add(locale.language) if locale.territory: # if a territory is specified, add that too - result.add("{}_{}".format(locale.language, locale.territory)) + result.add(f"{locale.language}_{locale.territory}") return result @@ -1495,7 +1490,7 @@ class Server: tag += ' target="_blank" rel="noreferrer noopener"' content = match.group("content") - return "<{tag}>{content}".format(tag=tag, content=content) + return f"<{tag}>{content}" return html_link_regex.sub(repl, text) @@ -1820,7 +1815,7 @@ class Server: if plugin.is_blueprint_protected(): blueprint.before_request(requireLoginRequestHandler) - url_prefix = "/plugin/{name}".format(name=name) + url_prefix = f"/plugin/{name}" app.register_blueprint(blueprint, url_prefix=url_prefix) if self._logger: @@ -1835,7 +1830,7 @@ class Server: def _prepare_asset_plugin(self, plugin): name = plugin._identifier - url_prefix = "/plugin/{name}".format(name=name) + url_prefix = f"/plugin/{name}" blueprint = Blueprint( "plugin." + name, name, static_folder=plugin.get_asset_folder() ) @@ -1895,7 +1890,7 @@ class Server: cli_key_file = os.path.join(self._settings.getBaseFolder("generated"), "cli.key") cli_key = generate_api_key() - with io.open(cli_key_file, "w", encoding="utf8") as f: + with open(cli_key_file, "w", encoding="utf8") as f: f.write(cli_key) return cli_key @@ -2178,7 +2173,7 @@ class Server: js_plugins_bundle = Bundle( *js_plugins.values(), output="webassets/packed_plugins.js", - filters=",".join(js_plugin_filters) + filters=",".join(js_plugin_filters), ) js_app_bundle = Bundle( @@ -2191,7 +2186,7 @@ class Server: js_client_core_bundle = Bundle( *clientjs_core, output="webassets/packed_client_core.js", - filters=",".join(js_filters) + filters=",".join(js_filters), ) if len(clientjs_plugins) == 0: @@ -2200,7 +2195,7 @@ class Server: js_client_plugins_bundle = Bundle( *clientjs_plugins.values(), output="webassets/packed_client_plugins.js", - filters=",".join(js_plugin_filters) + filters=",".join(js_plugin_filters), ) js_client_bundle = Bundle( @@ -2231,7 +2226,7 @@ class Server: css_core_bundle = Bundle( *css_core, output="webassets/packed_core.css", - filters=",".join(css_filters) + filters=",".join(css_filters), ) if len(css_plugins) == 0: @@ -2240,7 +2235,7 @@ class Server: css_plugins_bundle = Bundle( *css_plugins, output="webassets/packed_plugins.css", - filters=",".join(css_filters) + filters=",".join(css_filters), ) css_app_bundle = Bundle( @@ -2265,7 +2260,7 @@ class Server: less_core_bundle = Bundle( *less_core, output="webassets/packed_core.less", - filters=",".join(less_filters) + filters=",".join(less_filters), ) if len(less_plugins) == 0: @@ -2274,7 +2269,7 @@ class Server: less_plugins_bundle = Bundle( *less_plugins, output="webassets/packed_plugins.less", - filters=",".join(less_filters) + filters=",".join(less_filters), ) less_app_bundle = Bundle( @@ -2290,13 +2285,13 @@ class Server: assets.register("js_client_core", js_client_core_bundle) for plugin, bundle in clientjs_plugins.items(): # register our collected clientjs plugin bundles so that they are bound to the environment - assets.register("js_client_plugin_{}".format(plugin), bundle) + assets.register(f"js_client_plugin_{plugin}", bundle) assets.register("js_client_plugins", js_client_plugins_bundle) assets.register("js_client", js_client_bundle) assets.register("js_core", js_core_bundle) for plugin, bundle in js_plugins.items(): # register our collected plugin bundles so that they are bound to the environment - assets.register("js_plugin_{}".format(plugin), bundle) + assets.register(f"js_plugin_{plugin}", bundle) assets.register("js_plugins", js_plugins_bundle) assets.register("js_app", js_app_bundle) assets.register("css_libs", css_libs_bundle) @@ -2387,7 +2382,7 @@ class Server: if not os.path.isfile(path): return "" - with io.open(path, "rb") as f: + with open(path, "rb") as f: data = f.read() return data @@ -2442,9 +2437,7 @@ class Server: if host == "::": if self._v6_only: - self._logger.debug( - "Starting intermediary server on http://[::]:{port}".format(port=port) - ) + self._logger.debug(f"Starting intermediary server on http://[::]:{port}") else: self._logger.debug( "Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format( @@ -2532,7 +2525,7 @@ class Server: return "{}: {}".format(plugin, definition["name"]) def permission_role(plugin, role): - return "plugin_{}_{}".format(plugin, role) + return f"plugin_{plugin}_{role}" def process_regular_permission(plugin_info, definition): permissions = [] @@ -2562,7 +2555,7 @@ class Server: plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, - *roles_and_permissions + *roles_and_permissions, ) setattr( octoprint.access.permissions.Permissions, @@ -2573,7 +2566,7 @@ class Server: plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, - *roles_and_permissions + *roles_and_permissions, ), ) @@ -2621,7 +2614,7 @@ class Server: postponed.append((plugin_info, p)) except Exception: self._logger.exception( - "Error while creating permission instance/s from {}".format(name) + f"Error while creating permission instance/s from {name}" ) # final resolution passes diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 59323a036..83b625e74 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -2,7 +2,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging from flask import ( @@ -118,7 +117,7 @@ def pluginData(name): raise except Exception: logging.getLogger(__name__).exception( - "Error calling SimpleApiPlugin {}".format(name), extra={"plugin": name} + f"Error calling SimpleApiPlugin {name}", extra={"plugin": name} ) return abort(500) @@ -160,7 +159,7 @@ def pluginCommand(name): raise except Exception: logging.getLogger(__name__).exception( - "Error while executing SimpleApiPlugin {}".format(name), + f"Error while executing SimpleApiPlugin {name}", extra={"plugin": name}, ) return abort(500) @@ -268,7 +267,7 @@ def apiVersion(): return jsonify( server=octoprint.server.VERSION, api=VERSION, - text="OctoPrint {}".format(octoprint.server.DISPLAY_VERSION), + text=f"OctoPrint {octoprint.server.DISPLAY_VERSION}", ) @@ -481,7 +480,7 @@ def _test_path(data): os.makedirs(path) except Exception: logging.getLogger(__name__).exception( - "Error while trying to create {}".format(path) + f"Error while trying to create {path}" ) return jsonify( path=path, @@ -514,12 +513,12 @@ def _test_path(data): if check_writable_dir and check_type == "dir": try: test_path = os.path.join(path, ".testballoon.txt") - with io.open(test_path, "wb") as f: + with open(test_path, "wb") as f: f.write(b"Test") os.remove(test_path) except Exception: logging.getLogger(__name__).exception( - "Error while testing if {} is really writable".format(path) + f"Error while testing if {path} is really writable" ) return jsonify( path=path, @@ -684,7 +683,7 @@ def _test_url(data): response_result["content"] = content except Exception: logging.getLogger(__name__).exception( - "Error while running a test {} request on {}".format(method, url) + f"Error while running a test {method} request on {url}" ) outcome = False diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index 4ad77af5e..9f61fe403 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -288,7 +288,7 @@ def _getFileList( ) with _file_cache_mutex: - cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter) + cache_key = f"{origin}:{path}:{recursive}:{filter}" files, lastmodified = _file_cache.get(cache_key, ([], None)) # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 if ( @@ -994,7 +994,7 @@ def gcodeFileCommand(filename, target): with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: - abort(400, description="Unsupported target for {}".format(command)) + abort(400, description=f"Unsupported target for {command}") if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename @@ -1026,9 +1026,7 @@ def gcodeFileCommand(filename, target): is_folder = fileManager.folder_exists(target, filename) if not (is_file or is_folder): - abort( - 400, description="Neither file nor folder, can't {}".format(command) - ) + abort(400, description=f"Neither file nor folder, can't {command}") if command == "copy": # destination already there? error... diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 7815cfdbd..8c86b6386 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -2,7 +2,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os import tarfile @@ -44,7 +43,7 @@ def getInstalledLanguagePacks(): import yaml try: - with io.open(meta_path, "rt", encoding="utf-8") as f: + with open(meta_path, encoding="utf-8") as f: meta = yaml.safe_load(f) except Exception: logging.getLogger(__name__).exception("Could not load %s", meta_path) diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 6e6b52eb3..bbe5576d0 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -142,14 +142,14 @@ def executeSystemCommand(source, command): ) ) else: - logger.info("Performing command for {}:{}".format(source, command)) + logger.info(f"Performing command for {source}:{command}") try: if "before" in command_spec and callable(command_spec["before"]): command_spec["before"]() except Exception as e: if not do_ignore: - error = 'Command "before" for {}:{} failed: {}'.format(source, command, e) + error = f'Command "before" for {source}:{command} failed: {e}' logger.warning(error) abort(500, description=error) @@ -192,7 +192,7 @@ def executeSystemCommand(source, command): except Exception as e: if not do_ignore: - error = "Command for {}:{} failed: {}".format(source, command, e) + error = f"Command for {source}:{command} failed: {e}" logger.warning(error) abort(500, error) @@ -297,7 +297,7 @@ def _get_custom_command_specs(): action = spec["action"] if action == "divider": dividers += 1 - action = "divider_{}".format(dividers) + action = f"divider_{dividers}" specs[action] = copied return specs diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 4bd38051a..6440eaa84 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -177,9 +177,9 @@ def deleteTimelapse(filename): os.remove(full_path) except Exception as ex: logging.getLogger(__file__).exception( - "Error deleting timelapse file {}".format(full_path) + f"Error deleting timelapse file {full_path}" ) - abort(500, description="Unexpected error: {}".format(ex)) + abort(500, description=f"Unexpected error: {ex}") return getTimelapseData() diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 2bffcb591..68b6f0812 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -318,7 +318,7 @@ def get_authorization_header(request): def get_plugin_hash(): from octoprint.plugin import plugin_manager - plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version) + plugin_signature = lambda impl: f"{impl._identifier}:{impl._plugin_version}" template_plugins = list( map( plugin_signature, diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index ffa3b956d..7b38990a9 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -5,7 +5,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import functools -import io import logging import os import threading @@ -151,9 +150,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None) ) break else: - logger.debug( - "No translations for locale {} in core folders".format(locale) - ) + logger.debug(f"No translations for locale {locale} in core folders") translations = translations.merge(core_translations) ctx.babel_translations = translations @@ -215,7 +212,7 @@ def fix_webassets_cache(): filename = os.path.join(self.directory, "%s" % hash) try: - f = io.open(filename, "rb") + f = open(filename, "rb") except OSError as e: if e.errno != errno.ENOENT: error_logger.exception( @@ -615,7 +612,7 @@ def _local_networks(): continue local_networks.add(network) - logger.debug("Added network {} to localNetworks".format(network)) + logger.debug(f"Added network {network} to localNetworks") if network.version == 4: network_v6 = network.ipv6() @@ -664,9 +661,7 @@ def passive_login(): def determine_user(u): if not u.is_anonymous and u.is_active: # known active user - logger.info( - "Passively logging in user {} from {}".format(u.get_id(), remote_address) - ) + logger.info(f"Passively logging in user {u.get_id()} from {remote_address}") elif ( settings().getBoolean(["accessControl", "autologinLocal"]) @@ -998,9 +993,7 @@ class PreemptiveCache: entries = cleanup_function(root, entries) if not entries: del all_data[root] - self._logger.debug( - "Removed root {} from preemptive cache".format(root) - ) + self._logger.debug(f"Removed root {root} from preemptive cache") elif len(entries) < old_count: all_data[root] = entries self._logger.debug( @@ -1018,7 +1011,7 @@ class PreemptiveCache: cache_data = None with self._lock: try: - with io.open(self.cachefile, "rt") as f: + with open(self.cachefile) as f: cache_data = yaml.safe_load(f) except OSError as e: import errno @@ -1026,7 +1019,7 @@ class PreemptiveCache: if e.errno != errno.ENOENT: raise except Exception: - self._logger.exception("Error while reading {}".format(self.cachefile)) + self._logger.exception(f"Error while reading {self.cachefile}") if cache_data is None: cache_data = {} @@ -1057,7 +1050,7 @@ class PreemptiveCache: allow_unicode=True, ) except Exception: - self._logger.exception("Error while writing {}".format(self.cachefile)) + self._logger.exception(f"Error while writing {self.cachefile}") def set_data(self, root, data): with self._lock: @@ -1106,12 +1099,12 @@ class PreemptiveCache: to_persist = copy.deepcopy(data) to_persist["_timestamp"] = time.time() to_persist["_count"] = 1 - self._logger.info("Adding entry for {} and {!r}".format(root, to_persist)) + self._logger.info(f"Adding entry for {root} and {to_persist!r}") else: to_persist["_timestamp"] = time.time() to_persist["_count"] = to_persist.get("_count", 0) + 1 self._logger.debug( - "Updating timestamp and counter for {} and {!r}".format(root, data) + f"Updating timestamp and counter for {root} and {data!r}" ) self.set_data(root, [to_persist] + other) @@ -1150,7 +1143,7 @@ def preemptively_cached(cache, data, unless=None): cache.record(data, unless=unless) except Exception: logging.getLogger(__name__).exception( - "Error while recording preemptive cache entry: {!r}".format(data) + f"Error while recording preemptive cache entry: {data!r}" ) return f(*args, **kwargs) diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 845810db6..ac6b33b9a 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -173,9 +173,9 @@ class PrinterStateConnection( def __str__(self): if self._remoteAddress: - return "{!r} connected to {}".format(self, self._remoteAddress) + return f"{self!r} connected to {self._remoteAddress}" else: - return "Unconnected {!r}".format(self) + return f"Unconnected {self!r}" def on_open(self, info): self._pluginManager.register_message_receiver(self.on_plugin_message) @@ -279,7 +279,7 @@ class PrinterStateConnection( self._on_login(user) else: self._logger.warning( - "Unknown user/session combo: {}:{}".format(user_id, user_session) + f"Unknown user/session combo: {user_id}:{user_session}" ) self._on_logout() @@ -437,9 +437,7 @@ class PrinterStateConnection( and hasattr(self._user, "session") and user.session == self._user.session ): - self._logger.info( - "User {} logged out, logging out on socket".format(user.get_id()) - ) + self._logger.info(f"User {user.get_id()} logged out, logging out on socket") self._on_logout() if stale: @@ -453,7 +451,7 @@ class PrinterStateConnection( def on_user_removed(self, userid): if self._user.get_id() == userid: - self._logger.info("User {} deleted, logging out on socket".format(userid)) + self._logger.info(f"User {userid} deleted, logging out on socket") self._on_logout() self._sendReauthRequired("removed") @@ -477,7 +475,7 @@ class PrinterStateConnection( proceed = proceed and hook(self, self._user) except Exception: self._logger.exception( - "Error processing register hook handler for plugin {}".format(name), + f"Error processing register hook handler for plugin {name}", extra={"plugin": name}, ) @@ -542,7 +540,7 @@ class PrinterStateConnection( proceed = proceed and hook(self, self._user, type, payload) except Exception: self._logger.exception( - "Error processing emit hook handler from plugin {}".format(name), + f"Error processing emit hook handler from plugin {name}", extra={"plugin": name}, ) @@ -585,7 +583,7 @@ class PrinterStateConnection( except Exception as e: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( - "Could not send message to client {}".format(self._remoteAddress) + f"Could not send message to client {self._remoteAddress}" ) else: self._logger.warning( @@ -608,7 +606,7 @@ class PrinterStateConnection( hook(self, self._user) except Exception: self._logger.exception( - "Error processing authed hook handler for plugin {}".format(name), + f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) @@ -641,6 +639,6 @@ class PrinterStateConnection( hook(self, self._user) except Exception: self._logger.exception( - "Error processing authed hook handler for plugin {}".format(name), + f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 37e082677..32ff80e25 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -1186,7 +1186,7 @@ class LargeResponseHandler( etag = str(self.get_content_version(self.absolute_path)) if not etag.endswith('"'): - etag = '"{}"'.format(etag) + etag = f'"{etag}"' return etag # noinspection PyAttributeOutsideInit @@ -1330,7 +1330,7 @@ class UrlProxyHandler( if not extension: return None - return "{}{}".format(self._basename, extension) + return f"{self._basename}{extension}" class StaticDataHandler( @@ -1373,7 +1373,7 @@ class DeprecatedEndpointHandler(CorsSupportMixin, tornado.web.RequestHandler): def _handle_method(self, *args, **kwargs): to_url = self._url.format(*args) self._logger.info( - "Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url) + f"Redirecting deprecated endpoint {self.request.path} to {to_url}" ) self.redirect(to_url, permanent=True) @@ -1431,7 +1431,7 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): if self._as_attachment: self.set_header( "Content-Disposition", - 'attachment; filename="{}"'.format(self.get_attachment_name()), + f'attachment; filename="{self.get_attachment_name()}"', ) import zipstream @@ -1576,7 +1576,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): self.set_header("Content-Type", "application/zip") self.set_header( "Content-Disposition", - 'attachment; filename="{}"'.format(get_systeminfo_bundle_name()), + f'attachment; filename="{get_systeminfo_bundle_name()}"', ) for chunk in z: diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index 3d0aa85dc..f060685e0 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -57,7 +57,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): if not self._valid_path(path): continue - self._logger.info("Found {}, trying to add it".format(path)) + self._logger.info(f"Found {path}, trying to add it") self._upload(path) self._logger.info("... initial scan done.") @@ -147,7 +147,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): # file is still there - that should only happen if something went wrong, so mark it as failed # noinspection PyBroadException try: - shutil.move(path, "{}.failed".format(path)) + shutil.move(path, f"{path}.failed") except Exception: # something went really wrong here.... but we can't do anything about it, so just log it self._logger.exception( @@ -190,7 +190,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): last_size = new_size time.sleep(interval) - self._logger.debug("File at {} is stable, moving it".format(path)) + self._logger.debug(f"File at {path} is stable, moving it") self._upload(path) def _valid_path(self, path): diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 4ba4a5254..04dcf1344 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -4,7 +4,6 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import base64 import datetime -import io import logging import os import re @@ -104,7 +103,7 @@ def _preemptive_data( d.update(data) except Exception: _logger.exception( - "Error collecting data for preemptive cache from plugin {}".format(key) + f"Error collecting data for preemptive cache from plugin {key}" ) # add additional request data if we have any @@ -129,7 +128,7 @@ def _cache_key(ui, url=None, locale=None, additional_key_data=None): if locale is None: locale = g.locale.language if g.locale else "en" - k = "ui:{}:{}:{}".format(ui, url, locale) + k = f"ui:{ui}:{url}:{locale}" if callable(additional_key_data): try: ak = additional_key_data() @@ -160,7 +159,7 @@ def _add_additional_assets(hook): result += assets except Exception: _logger.exception( - "Error fetching theming CSS to include from plugin {}".format(name), + f"Error fetching theming CSS to include from plugin {name}", extra={"plugin": name}, ) return result @@ -273,7 +272,7 @@ def in_cache(): break except Exception: _logger.exception( - "Error while calling plugin {}, skipping it".format(plugin._identifier), + f"Error while calling plugin {plugin._identifier}, skipping it", extra={"plugin": plugin._identifier}, ) else: @@ -297,9 +296,7 @@ def in_cache(): ) return response elif util.flask.is_in_cache(key): - _logger.info( - "Found path {} in cache (key: {}), signaling as cached".format(path, key) - ) + _logger.info(f"Found path {path} in cache (key: {key}), signaling as cached") return response elif util.flask.is_cache_bypassed(key): _logger.info( @@ -309,9 +306,7 @@ def in_cache(): ) return response else: - _logger.debug( - "Path {} not yet cached (key: {}), signaling as missing".format(path, key) - ) + _logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing") return abort(404) @@ -619,7 +614,7 @@ def index(): if forced_view: # we have view forced by the preemptive cache - _logger.debug("Forcing rendering of view {}".format(forced_view)) + _logger.debug(f"Forcing rendering of view {forced_view}") if forced_view != "_default": plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) if plugin is not None and isinstance( @@ -706,7 +701,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): permissions = [permission.as_dict() for permission in Permissions.all()] filetypes = list(sorted(full_extension_tree().keys())) - extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions())) + extensions = list(map(lambda ext: f".{ext}", get_all_extensions())) # ~~ prepare full set of template vars for rendering @@ -1684,7 +1679,7 @@ def _get_translations(locale, domain): def messages_from_po(path, locale, domain): messages = {} - with io.open(path, mode="rt", encoding="utf-8") as f: + with open(path, mode="rt", encoding="utf-8") as f: catalog = read_po(f, locale=locale, domain=domain) for message in catalog: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 92d6a4b74..c911a2b12 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -22,7 +22,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy import fnmatch -import io import logging import os import re @@ -976,7 +975,7 @@ class Settings: def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): - with io.open(self._configfile, "rt", encoding="utf-8", errors="replace") as f: + with open(self._configfile, encoding="utf-8", errors="replace") as f: try: self._config = yaml.safe_load(f) self._mtime = self.last_modified @@ -1017,11 +1016,9 @@ class Settings: try: overlay_config = self.load_overlay(path, migrate=migrate) self.add_overlay(overlay_config) - self._logger.info("Added config overlay from {}".format(path)) + self._logger.info(f"Added config overlay from {path}") except Exception: - self._logger.exception( - "Could not add config overlay from {}".format(path) - ) + self._logger.exception(f"Could not add config overlay from {path}") if os.path.isfile(overlay): process(overlay) @@ -1048,7 +1045,7 @@ class Settings: if isinstance(overlay, str): if os.path.exists(overlay) and os.path.isfile(overlay): - with io.open(overlay, "rt", encoding="utf-8", errors="replace") as f: + with open(overlay, encoding="utf-8", errors="replace") as f: config = yaml.safe_load(f) elif isinstance(overlay, dict): config = overlay @@ -1059,7 +1056,7 @@ class Settings: if not isinstance(config, dict): raise ValueError( - "Configuration data must be a dict but is a {}".format(config.__class__) + f"Configuration data must be a dict but is a {config.__class__}" ) if migrate: @@ -2000,7 +1997,7 @@ class Settings: preprocessors=None, error_on_path=False, *args, - **kwargs + **kwargs, ): if not path: if error_on_path: @@ -2185,7 +2182,7 @@ def _validate_folder( if not os.path.exists(folder): if os.path.islink(folder): # broken symlink, see #2644 - raise OSError("Folder at {} appears to be a broken symlink".format(folder)) + raise OSError(f"Folder at {folder} appears to be a broken symlink") elif create: # non existing, but we are allowed to create it @@ -2193,7 +2190,7 @@ def _validate_folder( os.makedirs(folder) except Exception: if log_error: - logger.exception("Could not create {}".format(folder)) + logger.exception(f"Could not create {folder}") raise OSError( "Folder for type {} at {} does not exist and creation failed".format( type, folder @@ -2202,11 +2199,11 @@ def _validate_folder( else: # not extisting, not allowed to create it - raise OSError("No such folder: {}".format(folder)) + raise OSError(f"No such folder: {folder}") elif os.path.isfile(folder): # hardening against misconfiguration, see #1953 - raise OSError("Expected a folder at {} but found a file instead".format(folder)) + raise OSError(f"Expected a folder at {folder} but found a file instead") elif check_writable: # make sure we can also write into the folder @@ -2221,10 +2218,10 @@ def _validate_folder( # to determine whether things are *actually* writable testfile = os.path.join(folder, ".testballoon.txt") try: - with io.open(testfile, "wt", encoding="utf-8") as f: + with open(testfile, "wt", encoding="utf-8") as f: f.write("test") os.remove(testfile) except Exception: if log_error: - logger.exception("Could not write test file to {}".format(folder)) + logger.exception(f"Could not write test file to {folder}") raise OSError(error) diff --git a/src/octoprint/slicing/__init__.py b/src/octoprint/slicing/__init__.py index c22f74b7a..a005ff8fb 100644 --- a/src/octoprint/slicing/__init__.py +++ b/src/octoprint/slicing/__init__.py @@ -724,9 +724,7 @@ class SlicingManager: name = self._sanitize(name) - path = os.path.join( - self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name) - ) + path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile") if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)): raise OSError( "Path to profile {name} tried to break out of allows sub path".format( diff --git a/src/octoprint/slicing/exceptions.py b/src/octoprint/slicing/exceptions.py index 7d0d68287..0036890bb 100644 --- a/src/octoprint/slicing/exceptions.py +++ b/src/octoprint/slicing/exceptions.py @@ -67,7 +67,7 @@ class SlicerNotConfigured(SlicerException): def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) - self.message = "Slicer not configured: {slicer}".format(slicer=slicer) + self.message = f"Slicer not configured: {slicer}" class UnknownSlicer(SlicerException): @@ -77,7 +77,7 @@ class UnknownSlicer(SlicerException): def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) - self.message = "No such slicer: {slicer}".format(slicer=slicer) + self.message = f"No such slicer: {slicer}" class ProfileException(Exception): diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 637a78859..3117f9384 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -5,7 +5,6 @@ import collections import datetime import fnmatch import glob -import io import logging import os import queue @@ -201,7 +200,7 @@ def delete_unrendered_timelapse(name): except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( - "Error while processing file {} during cleanup".format(entry.name) + f"Error while processing file {entry.name} during cleanup" ) @@ -259,14 +258,12 @@ def delete_old_unrendered_timelapses(): except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( - "Error while processing file {} during cleanup".format(entry.name) + f"Error while processing file {entry.name} during cleanup" ) for prefix in prefixes_to_clean: delete_unrendered_timelapse(prefix) - logging.getLogger(__name__).info( - "Deleted old unrendered timelapse {}".format(prefix) - ) + logging.getLogger(__name__).info(f"Deleted old unrendered timelapse {prefix}") def _create_render_start_handler(name, gcode=None): @@ -682,7 +679,7 @@ class Timelapse: ) self._image_number += 1 - self._logger.debug("Capturing image to {}".format(filename)) + self._logger.debug(f"Capturing image to {filename}") entry = { "type": self.__class__.QUEUE_ENTRY_TYPE_CAPTURE, "filename": filename, @@ -728,9 +725,7 @@ class Timelapse: eventManager().fire(Events.CAPTURE_START, {"file": filename}) try: - self._logger.debug( - "Going to capture {} from {}".format(filename, self._snapshot_url) - ) + self._logger.debug(f"Going to capture {filename} from {self._snapshot_url}") r = requests.get( self._snapshot_url, stream=True, @@ -739,18 +734,16 @@ class Timelapse: ) r.raise_for_status() - with io.open(filename, "wb") as f: + with open(filename, "wb") as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() - self._logger.debug( - "Image {} captured from {}".format(filename, self._snapshot_url) - ) + self._logger.debug(f"Image {filename} captured from {self._snapshot_url}") except Exception as e: self._logger.exception( - "Could not capture image {} from {}".format(filename, self._snapshot_url) + f"Could not capture image {filename} from {self._snapshot_url}" ) self._capture_errors += 1 err = e @@ -993,7 +986,7 @@ class TimelapseRenderJob: postfix=self._postfix if self._postfix is not None else "", extension=extension, ) - temporary = os.path.join(self._output_dir, ".{}".format(output_name)) + temporary = os.path.join(self._output_dir, f".{output_name}") output = os.path.join(self._output_dir, output_name) for i in range(4): @@ -1034,7 +1027,7 @@ class TimelapseRenderJob: rotate=rotate, watermark=watermark, ) - self._logger.debug("Executing command: {}".format(command_str)) + self._logger.debug(f"Executing command: {command_str}") with self.render_job_lock: try: @@ -1075,7 +1068,7 @@ class TimelapseRenderJob: os.remove(temporary) except Exception: self._logger.warning( - "Could not delete temporary timelapse {}".format(temporary) + f"Could not delete temporary timelapse {temporary}" ) self._notify_callback("always", output) @@ -1155,7 +1148,7 @@ class TimelapseRenderJob: "-framerate", str(fps), "-i", - '"{}"'.format(input), + f'"{input}"', "-vcodec", videocodec, "-threads", @@ -1174,12 +1167,12 @@ class TimelapseRenderJob: ) if filter_string is not None: - logger.debug("Applying videofilter chain: {}".format(filter_string)) + logger.debug(f"Applying videofilter chain: {filter_string}") command.extend(["-vf", sarge.shell_quote(filter_string)]) # finalize command with output file - logger.debug("Rendering movie to {}".format(output)) - command.append('"{}"'.format(output)) + logger.debug(f"Rendering movie to {output}") + command.append(f'"{output}"') return " ".join(command) @@ -1204,7 +1197,7 @@ class TimelapseRenderJob: ### See unit tests in test/timelapse/test_timelapse_renderjob.py # apply pixel format - filters = ["format={}".format(pixfmt)] + filters = [f"format={pixfmt}"] # flip video if configured if hflip: @@ -1236,7 +1229,7 @@ class TimelapseRenderJob: def _notify_callback(self, callback, *args, **kwargs): """Notifies registered callbacks of type `callback`.""" - name = "_on_{}".format(callback) + name = f"_on_{callback}" method = getattr(self, name, None) if method is not None and callable(method): method(*args, **kwargs) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 3ef281f2c..143e5111d 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -10,7 +10,6 @@ import collections import contextlib import copy import glob -import io import logging import os import queue @@ -334,7 +333,7 @@ def get_formatted_size(num): for x in ["B", "KB", "MB", "GB"]: if num < 1024: - return "{:3.1f}{}".format(num, x) + return f"{num:3.1f}{x}" num /= 1024 return "{:3.1f}{}".format(num, "TB") @@ -1253,7 +1252,7 @@ else: os.remove(self._path) except Exception as exc: logging.getLogger(__name__).warning( - "Could not delete temporary directory {}: {}".format(self.name, exc) + f"Could not delete temporary directory {self.name}: {exc}" ) def __enter__(self): @@ -1279,13 +1278,13 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs): # these encodings might have a BOM, so let's see if there is one bom = getattr(codecs, potential_bom_attribute) - with io.open(filename, mode="rb") as f: + with open(filename, mode="rb") as f: header = f.read(4) if header.startswith(bom): encoding += "-sig" - return io.open(filename, encoding=encoding, mode=mode, **kwargs) + return open(filename, encoding=encoding, mode=mode, **kwargs) def is_hidden_path(path): @@ -1764,7 +1763,7 @@ class TypedQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -1785,7 +1784,7 @@ class TypedQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -1842,7 +1841,7 @@ def fqfn(f): f.__self__.__class__.__module__, f.__self__.__class__.__name__, f.__name__ ) else: - return "{}.{}".format(f.__module__, f.__name__) + return f"{f.__module__}.{f.__name__}" def time_this( diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 154255124..b41965569 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -158,9 +158,7 @@ Groups will be as follows: * ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions """ -regex_e_positions = re.compile( - r"E(?P\d+):\s*(?P{float})".format(float=regex_float_pattern) -) +regex_e_positions = re.compile(fr"E(?P\d+):\s*(?P{regex_float_pattern})") """Regex for matching multiple E coordinates in a position report. Groups will be as follows: @@ -248,7 +246,7 @@ def baudrateList(candidates=None): candidates.insert(0, int(additional)) except Exception: _logger.warning( - "{} is not a valid additional baudrate, ignoring it".format(additional) + f"{additional} is not a valid additional baudrate, ignoring it" ) # blacklisted baudrates @@ -354,7 +352,7 @@ class TemperatureRecord: def set_custom(self, identifier, actual=None, target=None): if self.RESERVED_IDENTIFIER_REGEX.match(identifier): - raise ValueError("{} is a reserved identifier".format(identifier)) + raise ValueError(f"{identifier} is a reserved identifier") current = self._custom.get(identifier, (None, None)) self._custom[identifier] = self._to_new_tuple(current, actual, target) @@ -869,7 +867,7 @@ class MachineCom: def _to_logfile_with_terminal(self, message=None, level=logging.INFO): log = "Last lines in terminal:\n" + "\n".join( - map(lambda x: "| {}".format(x), list(self._terminal_log)) + map(lambda x: f"| {x}", list(self._terminal_log)) ) if message is not None: log = message + "\n| " + log @@ -942,7 +940,7 @@ class MachineCom: return "Offline after error" elif state == self.STATE_TRANSFERING_FILE: return "Transferring file to SD" - return "Unknown State ({})".format(self._state) + return f"Unknown State ({self._state})" def getErrorString(self): return self._errorValue @@ -1305,7 +1303,7 @@ class MachineCom: else: return None - additional_tags = {"plugin:{}".format(name)} + additional_tags = {f"plugin:{name}"} if len(retval) == 4: additional_tags |= set(retval[3]) @@ -1356,7 +1354,7 @@ class MachineCom: tags_to_use = tags | { "trigger:comm.send_gcode_script", "source:script", - "script:{}".format(scriptName), + f"script:{scriptName}", } for line in scriptLines: if ( @@ -1401,7 +1399,7 @@ class MachineCom: "Starting job on behalf of plugin {}".format(tag[7:]) ) elif "source:api" in tags: - self._logger.info("Starting job on behalf of user {}".format(user)) + self._logger.info(f"Starting job on behalf of user {user}") try: with self._jobLock: @@ -1435,7 +1433,7 @@ class MachineCom: if pos is not None and isinstance(pos, int) and pos > 0: self._currentFile.pos = pos self.sendCommand( - "M26 S{}".format(pos), + f"M26 S{pos}", part_of_job=True, tags=tags | { @@ -1650,7 +1648,7 @@ class MachineCom: "Cancelling job on behalf of plugin {}".format(tag[7:]) ) elif "source:api" in tags: - self._logger.info("Cancelling job on behalf of user {}".format(user)) + self._logger.info(f"Cancelling job on behalf of user {user}") if self.isStreaming(): # we are streaming, we handle cancelling that differently... @@ -1787,7 +1785,7 @@ class MachineCom: "Pausing/resuming job on behalf of plugin {}".format(tag[7:]) ) elif user: - self._logger.info("Pausing/resuming job on behalf of user {}".format(user)) + self._logger.info(f"Pausing/resuming job on behalf of user {user}") valid_paused_states = (self.STATE_PAUSED, self.STATE_PAUSING) valid_running_states = ( @@ -2005,7 +2003,7 @@ class MachineCom: tags = set() self.sendCommand( - "M110 N{}".format(number), + f"M110 N{number}", part_of_job=part_of_job, tags=tags | { @@ -2052,7 +2050,7 @@ class MachineCom: return except Exception: self._logger.exception( - "Error while processing temperatures in {}, skipping".format(name), + f"Error while processing temperatures in {name}, skipping", extra={"plugin": name}, ) @@ -2462,7 +2460,7 @@ class MachineCom: else: # multiple extruder coordinates provided, find current one self.last_position.e = ( - parsed.get("e{}".format(self._currentTool)) + parsed.get(f"e{self._currentTool}") if not self.isSdFileSelected() else None ) @@ -2590,7 +2588,7 @@ class MachineCom: if not self._firmware_info_received and firmware_name: firmware_name = firmware_name.strip() self._logger.info( - 'Printer reports firmware name "{}"'.format(firmware_name) + f'Printer reports firmware name "{firmware_name}"' ) if self._firmware_detection: @@ -2755,7 +2753,7 @@ class MachineCom: # we actually do send a T command here instead of just settings self._currentTool just in case # we had any scripts or plugins modify stuff due to the prior tool change self.sendCommand( - "T{}".format(fallback_tool), + f"T{fallback_tool}", tags={ "trigger:revert_invalid_tool", }, @@ -3074,9 +3072,7 @@ class MachineCom: # now increment the timeout counter self._consecutive_timeouts += 1 - self._logger.debug( - "Now at {} consecutive timeouts".format(self._consecutive_timeouts) - ) + self._logger.debug(f"Now at {self._consecutive_timeouts} consecutive timeouts") if 0 < consecutive_max < self._consecutive_timeouts: # too many consecutive timeouts, we give up @@ -3133,7 +3129,7 @@ class MachineCom: def _perform_detection_step(self, init=False): def log(message): self._log(message) - self._logger.info("Serial detection: {}".format(message)) + self._logger.info(f"Serial detection: {message}") if init: port = self._port @@ -3191,7 +3187,7 @@ class MachineCom: ) ) self._logger.exception( - "Unexpected error while setting timeout {}".format(timeout) + f"Unexpected error while setting timeout {timeout}" ) else: self._do_send_without_checksum(b"", log=False) # new line to reset things @@ -3220,7 +3216,7 @@ class MachineCom: (p, b) = self._detection_candidates.pop(0) try: - log("Trying port {}, baudrate {}".format(p, b)) + log(f"Trying port {p}, baudrate {b}") if self._serial is None or self._serial.port != p: if not self._open_serial(p, b, trigger_errors=False): log( @@ -3243,9 +3239,7 @@ class MachineCom: b, get_exception_string() ) ) - self._logger.exception( - "Unexpected error while setting baudrate {}".format(b) - ) + self._logger.exception(f"Unexpected error while setting baudrate {b}") error_text = "No more candidates to test, and no working port/baudrate combination detected." self._trigger_error(error_text, "autodetect") @@ -3405,7 +3399,7 @@ class MachineCom: except Exception: interval = 2 self.sendCommand( - "M155 S{}".format(interval), + f"M155 S{interval}", tags={"trigger:comm.set_autoreport_temperature_interval"}, ) @@ -3416,7 +3410,7 @@ class MachineCom: except Exception: interval = 1 self.sendCommand( - "M27 S{}".format(interval), + f"M27 S{interval}", tags={"trigger:comm.set_autoreport_sdstatus_interval"}, ) @@ -3429,7 +3423,7 @@ class MachineCom: except Exception: interval = 2 self.sendCommand( - "M113 S{}".format(interval), + f"M113 S{interval}", tags={"trigger:comm.set_busy_protocol_interval"}, on_sent=callback, ) @@ -3601,7 +3595,7 @@ class MachineCom: def default(_, p, b, timeout): # connect to regular serial port self._dual_log( - "Connecting to port {}, baudrate {}".format(port, baudrate), + f"Connecting to port {port}, baudrate {baudrate}", level=logging.INFO, ) @@ -3841,8 +3835,8 @@ class MachineCom: try: self._log("Recv: {}".format(sanitize_ascii(ret))) except ValueError as e: - self._log("WARN: While reading last line: {}".format(e)) - self._log("Recv: {!r}".format(ret)) + self._log(f"WARN: While reading last line: {e}") + self._log(f"Recv: {ret!r}") if null_pos >= 0: self._logger.warning("Received line:") @@ -3925,8 +3919,8 @@ class MachineCom: line, tags={ "source:file", - "filepos:{}".format(pos), - "fileline:{}".format(lineno), + f"filepos:{pos}", + f"fileline:{lineno}", }, ) self._callback.on_comm_progress() @@ -4419,7 +4413,7 @@ class MachineCom: def _log_command_phase(self, phase, command, *args, **kwargs): if self._phaseLogger.isEnabledFor(logging.DEBUG): output_parts = [ - "phase: {}".format(phase), + f"phase: {phase}", "command: {}".format(to_unicode(command, errors="replace")), ] @@ -4494,8 +4488,8 @@ class MachineCom: hook_results, tags_to_add={ "source:rewrite", - "phase:{}".format(phase), - "plugin:{}".format(name), + f"phase:{phase}", + f"plugin:{name}", }, ) @@ -4598,7 +4592,7 @@ class MachineCom: ) # trigger built-in handler if available - handler = getattr(self, "_atcommand_{}_{}".format(atcommand, phase), None) + handler = getattr(self, f"_atcommand_{atcommand}_{phase}", None) if callable(handler): try: handler(atcommand, parameters, tags=tags) @@ -4931,7 +4925,7 @@ class MachineCom: wait=False, support_r=False, *args, - **kwargs + **kwargs, ): toolNum = self._currentTool toolMatch = regexes_parameters["intT"].search(cmd) @@ -4969,7 +4963,7 @@ class MachineCom: wait=False, support_r=False, *args, - **kwargs + **kwargs, ): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: @@ -4997,7 +4991,7 @@ class MachineCom: wait=False, support_r=False, *args, - **kwargs + **kwargs, ): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: @@ -5087,7 +5081,7 @@ class MachineCom: with self._line_mutex: self._logger.info( - "M110 detected, setting current line number to {}".format(newLineNumber) + f"M110 detected, setting current line number to {newLineNumber}" ) # send M110 command with new line number @@ -5115,9 +5109,7 @@ class MachineCom: for tool in range( self._printerProfileManager.get_current_or_default()["extruder"]["count"] ): - self._do_increment_and_send_with_checksum( - "M104 T{tool} S0".format(tool=tool).encode("ascii") - ) + self._do_increment_and_send_with_checksum(f"M104 T{tool} S0".encode("ascii")) if self._printerProfileManager.get_current_or_default()["heatedBed"]: self._do_increment_and_send_with_checksum(b"M140 S0") @@ -5222,10 +5214,10 @@ class MachineCom: if gcode in self._emergency_commands and gcode != "M112": return self._emergency_force_send( cmd, - "Force-sending {} to the printer".format(gcode), + f"Force-sending {gcode} to the printer", gcode=gcode, *args, - **kwargs + **kwargs, ) if ( @@ -5234,7 +5226,7 @@ class MachineCom: and "trigger:cancel" not in tags and "trigger:pause" not in tags ): - self._logger.info("Pausing print job due to command {}".format(gcode)) + self._logger.info(f"Pausing print job due to command {gcode}") self.setPause(True) if gcode in self._blocked_commands: @@ -5515,9 +5507,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): """ with self._handle_mutex: if self._handle is None: - self._logger.warning( - "File {} is not open for reading".format(self._filename) - ) + self._logger.warning(f"File {self._filename} is not open for reading") return None, None, None try: @@ -5563,7 +5553,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): def _report_stats(self): duration = time.monotonic() - self._start_time - self._logger.info("Finished in {:.3f} s.".format(duration)) + self._logger.info(f"Finished in {duration:.3f} s.") pass @@ -5731,7 +5721,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -5748,7 +5738,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -5879,11 +5869,7 @@ def convert_pause_triggers(configured_triggers): for t in triggers.keys(): if len(triggers[t]) > 0: result[t] = re.compile( - "|".join( - map( - lambda pattern: "({pattern})".format(pattern=pattern), triggers[t] - ) - ) + "|".join(map(lambda pattern: f"({pattern})", triggers[t])) ) return result @@ -6500,14 +6486,12 @@ def upload_cli(): def on_comm_file_transfer_started(self, filename, filesize, user=None): # transfer started, report - _logger.info( - "Started file transfer of {}, size {}B".format(filename, filesize) - ) + _logger.info(f"Started file transfer of {filename}, size {filesize}B") self.started = True def on_comm_file_transfer_done(self, filename): # transfer done, report, print stats and finish - _logger.info("Finished file transfer of {}".format(filename)) + _logger.info(f"Finished file transfer of {filename}") self.finished.set() def on_comm_state_change(self, state): diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index 809c8d26d..68b58b1ec 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -162,7 +162,7 @@ class CommandlineCaller: joined_command = " ".join(command) else: joined_command = command - self._logger.debug("Calling: {}".format(joined_command)) + self._logger.debug(f"Calling: {joined_command}") self.on_log_call(joined_command) delimiter = kwargs.get("delimiter", b"\n") @@ -200,9 +200,7 @@ class CommandlineCaller: if not p.commands[0].process: # the process might have been set to None in case of any exception - self._logger.error( - "Error while trying to run command {}".format(joined_command) - ) + self._logger.error(f"Error while trying to run command {joined_command}") return None, [], [] all_stdout = [] diff --git a/src/octoprint/util/connectivity.py b/src/octoprint/util/connectivity.py index 8059c90cf..eaa39267c 100644 --- a/src/octoprint/util/connectivity.py +++ b/src/octoprint/util/connectivity.py @@ -168,7 +168,7 @@ class ConnectivityChecker: "online": self.online, "enabled": self.enabled, "connection_ok": self._connection_working, - "connection_check": "{}:{}".format(self._host, self._port), + "connection_check": f"{self._host}:{self._port}", } if self._name: result.update( @@ -208,9 +208,7 @@ class ConnectivityChecker: if self._name: if connection_working: - self._logger.debug( - "Checking if we can resolve {}...".format(self._name) - ) + self._logger.debug(f"Checking if we can resolve {self._name}...") resolution_working = len(resolve_host(self._name)) > 0 else: resolution_working = False diff --git a/src/octoprint/util/dev.py b/src/octoprint/util/dev.py index 7100747cc..d3270a431 100644 --- a/src/octoprint/util/dev.py +++ b/src/octoprint/util/dev.py @@ -67,7 +67,7 @@ def log_duration(log=None, with_args=False): arguments = "".join([args_str, sep, kwargs_str]) else: arguments = "..." - context = "{name}({arguments})".format(name=f.__name__, arguments=arguments) + context = f"{f.__name__}({arguments})" with duration_log(context=context, log=log): return f(*args, **kwargs) diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py index 911ae2eea..8f9cd05ca 100644 --- a/src/octoprint/util/net.py +++ b/src/octoprint/util/net.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os import socket @@ -57,7 +56,7 @@ def get_lan_ranges(additional_private=None): _, prefix = prefix.split("/") addr = strip_interface_tag(address["addr"]) - return netaddr.IPNetwork("{}/{}".format(addr, prefix)) + return netaddr.IPNetwork(f"{addr}/{prefix}") subnets = [] @@ -260,7 +259,7 @@ def download_file(url, folder, max_length=None): path = os.path.abspath(os.path.join(folder, filename)) assert path.startswith(folder) - with io.open(path, "wb") as f: + with open(path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) return path diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py index d0013c09a..67f27cbb7 100644 --- a/src/octoprint/util/pip.py +++ b/src/octoprint/util/pip.py @@ -72,9 +72,7 @@ class PipCaller(CommandlineCaller): # add --no-use-wheel for versions that otherwise break if pip_version in cls.no_use_wheel and "--no-use-wheel" not in args: - logger.debug( - "Version {} needs --no-use-wheel to properly work.".format(pip_version) - ) + logger.debug(f"Version {pip_version} needs --no-use-wheel to properly work.") args.append("--no-use-wheel") # remove --user if it's present and a virtual env is detected @@ -333,7 +331,7 @@ class PipCaller(CommandlineCaller): with _cache_mutex: if not self.ignore_cache and pip_command_str in _cache["version"]: self._logger.debug( - "Using cached pip version information for {}".format(pip_command_str) + f"Using cached pip version information for {pip_command_str}" ) return _cache["version"][pip_command_str] @@ -347,7 +345,7 @@ class PipCaller(CommandlineCaller): if p.returncode != 0: self._logger.warning( - "Error while trying to run pip --version: {}".format(p.stderr.text) + f"Error while trying to run pip --version: {p.stderr.text}" ) return None, None @@ -383,7 +381,7 @@ class PipCaller(CommandlineCaller): ) return None, None - self._logger.info("Version of pip is {}".format(version_segment)) + self._logger.info(f"Version of pip is {version_segment}") result = pip_version, version_segment _cache["version"][pip_command_str] = result @@ -397,7 +395,7 @@ class PipCaller(CommandlineCaller): with _cache_mutex: if not self.ignore_cache and pip_command_str in _cache["setup"]: self._logger.debug( - "Using cached pip setup information for {}".format(pip_command_str) + f"Using cached pip setup information for {pip_command_str}" ) return _cache["setup"][pip_command_str] diff --git a/src/octoprint/util/piptestballoon/setup.py b/src/octoprint/util/piptestballoon/setup.py index a95966768..c0e26335d 100644 --- a/src/octoprint/util/piptestballoon/setup.py +++ b/src/octoprint/util/piptestballoon/setup.py @@ -26,9 +26,9 @@ virtual_env = hasattr(sys, "real_prefix") or ( writable = os.access(install_dir, os.W_OK) lines = [ - "PIP_INSTALL_DIR={}".format(install_dir), - "PIP_VIRTUAL_ENV={}".format(virtual_env), - "PIP_WRITABLE={}".format(writable), + f"PIP_INSTALL_DIR={install_dir}", + f"PIP_VIRTUAL_ENV={virtual_env}", + f"PIP_WRITABLE={writable}", ] # write to stdout diff --git a/src/octoprint/util/version.py b/src/octoprint/util/version.py index 792d66eb5..62e4bce58 100644 --- a/src/octoprint/util/version.py +++ b/src/octoprint/util/version.py @@ -106,7 +106,7 @@ def is_octoprint_compatible(*compatibility_entries, **kwargs): octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===") ): - octo_compat = ">={}".format(octo_compat) + octo_compat = f">={octo_compat}" s = pkg_resources.Requirement.parse("OctoPrint" + octo_compat) if octoprint_version in s: diff --git a/src/octoprint_client/__init__.py b/src/octoprint_client/__init__.py index 6b5fafb73..6ce5df44f 100644 --- a/src/octoprint_client/__init__.py +++ b/src/octoprint_client/__init__.py @@ -1,7 +1,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import json import time @@ -13,12 +12,12 @@ def build_base_url( https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None ): protocol = "https" if https else "http" - httpauth = "{}:{}@".format(httpuser, httppass) if httpuser and httppass else "" + httpauth = f"{httpuser}:{httppass}@" if httpuser and httppass else "" host = host if host else "127.0.0.1" - port = ":{}".format(port) if port else ":5000" + port = f":{port}" if port else ":5000" prefix = prefix if prefix else "" - return "{}://{}{}{}{}".format(protocol, httpauth, host, port, prefix) + return f"{protocol}://{httpauth}{host}{port}{prefix}" class SocketTimeout(BaseException): @@ -287,14 +286,12 @@ class Client: import os if not os.path.isfile(file_path): - raise ValueError( - "{} cannot be uploaded since it is not a file".format(file_path) - ) + raise ValueError(f"{file_path} cannot be uploaded since it is not a file") if file_name is None: file_name = os.path.basename(file_path) - with io.open(file_path, "rb") as fp: + with open(file_path, "rb") as fp: if content_type: files = {"file": (file_name, fp, content_type)} else: @@ -411,7 +408,7 @@ class Client: class CustomSocketClient(SocketClient): def auth(self, username, key): - self.send({"auth": "{}:{}".format(username, key)}) + self.send({"auth": f"{username}:{key}"}) def throttle(self, factor): self.send({"throttle": factor}) diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 682ee5d0a..80feb3acf 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -485,9 +485,9 @@ class PackTranslation(Command): print("Adding {entry_path} as {new_prefix}".format(**locals())) zip.write(entry_path, new_prefix) - meta_str = "last_update: {date}\n".format(date=now.isoformat()) + meta_str = f"last_update: {now.isoformat()}\n" if self.author: - meta_str += "author: {author}\n".format(author=self.author) + meta_str += f"author: {self.author}\n" zip_locale_root = self.__class__.pack_path_prefix + locale @@ -636,7 +636,7 @@ def create_plugin_setup_parameters( [package] + list( filter( - lambda x: x.startswith("{package}.".format(package=package)), + lambda x: x.startswith(f"{package}."), find_packages(where=source_folder, exclude=ignored_packages), ) ) diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index 4fd944d44..4d396b1ce 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -2,7 +2,6 @@ __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os import os.path import unittest @@ -23,7 +22,7 @@ class FileWrapper: blocksize = 65536 hash = hashlib.sha1() - with io.open(self.path, "rb") as f: + with open(self.path, "rb") as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -829,7 +828,7 @@ class LocalStorageTest(unittest.TestCase): # prepare import yaml - with io.open(yaml_path, "wt") as f: + with open(yaml_path, "wt") as f: yaml.safe_dump(metadata, f) # migrate @@ -841,7 +840,7 @@ class LocalStorageTest(unittest.TestCase): import json - with io.open(json_path, "rt", encoding="utf-8") as f: + with open(json_path, encoding="utf-8") as f: json_metadata = json.load(f) self.assertDictEqual(metadata, json_metadata) diff --git a/tests/plugin/test_settings.py b/tests/plugin/test_settings.py index 24de2a1f0..200b252a4 100644 --- a/tests/plugin/test_settings.py +++ b/tests/plugin/test_settings.py @@ -161,8 +161,7 @@ class SettingsTestCase(unittest.TestCase): self.assertEqual(1, len(w)) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue( - "{old} has been renamed to {new}".format(old=deprecated, new=current) - in str(w[-1].message) + f"{deprecated} has been renamed to {current}" in str(w[-1].message) ) @data( @@ -402,8 +401,7 @@ class SettingsTestCase(unittest.TestCase): self.assertEqual(1, len(w)) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue( - "{old} has been renamed to {new}".format(old=deprecated, new=current) - in str(w[-1].message) + f"{deprecated} has been renamed to {current}" in str(w[-1].message) ) def test_global_get_basefolder(self): @@ -419,7 +417,7 @@ class SettingsTestCase(unittest.TestCase): self.settings.getBaseFolder.assert_called_once_with("logs") self.assertEqual( - "/some/folder/plugin_{key}.log".format(key=self.plugin_key), + f"/some/folder/plugin_{self.plugin_key}.log", path.replace(os.sep, "/"), ) @@ -432,7 +430,7 @@ class SettingsTestCase(unittest.TestCase): self.settings.getBaseFolder.assert_called_once_with("logs") self.assertEqual( - "/some/folder/plugin_{key}_mypostfix.log".format(key=self.plugin_key), + f"/some/folder/plugin_{self.plugin_key}_mypostfix.log", path.replace(os.sep, "/"), ) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 1457acb0b..dc8bd7b0a 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -10,7 +10,6 @@ Tests for OctoPrint's Settings class import contextlib import hashlib -import io import os import re import shutil @@ -27,11 +26,11 @@ import octoprint.settings @ddt.ddt class TestSettings(unittest.TestCase): def _load_yaml(self, fname): - with io.open(fname, "rt", encoding="utf-8") as f: + with open(fname, encoding="utf-8") as f: return yaml.safe_load(f) def _dump_yaml(self, fname, config): - with io.open(fname, "wt", encoding="utf-8") as f: + with open(fname, "wt", encoding="utf-8") as f: yaml.safe_dump(config, f) def setUp(self): @@ -182,7 +181,7 @@ class TestSettings(unittest.TestCase): # can switch to assertIsNone after 3.x upgrade. self.assertFalse( match_result, - "string matched and it shouldn't have: {!r}".format(terminal_string), + f"string matched and it shouldn't have: {terminal_string!r}", ) def test_temperature_regex_matches(self): @@ -208,7 +207,7 @@ class TestSettings(unittest.TestCase): # can switch to assertIsNotNone after 3.x upgrade. self.assertTrue( match_result, - "string did not match and it should have: {!r}".format(terminal_string), + f"string did not match and it should have: {terminal_string!r}", ) ##~~ test getters diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 303d510a3..98a69ff1d 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -403,7 +403,7 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( _fixups.OPEN_SIGNATURE, - mock.mock_open(read_data="{}\n".format(pid)), + mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: result = self.daemon.get_pid() @@ -432,7 +432,7 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( _fixups.OPEN_SIGNATURE, - mock.mock_open(read_data="{}\n".format(pid)), + mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: result = self.daemon.get_pid() @@ -452,7 +452,7 @@ class DaemonTest(unittest.TestCase): # assert m.assert_called_once_with(self.pidfile, "wt+", encoding="utf-8") handle = m() - handle.write.assert_called_once_with("{}\n".format(pid)) + handle.write.assert_called_once_with(f"{pid}\n") def test_set_pid_int(self): # setup @@ -465,7 +465,7 @@ class DaemonTest(unittest.TestCase): # assert m.assert_called_once_with(self.pidfile, "wt+", encoding="utf-8") handle = m() - handle.write.assert_called_once_with("{}\n".format(pid)) + handle.write.assert_called_once_with(f"{pid}\n") @mock.patch("os.path.isfile") @mock.patch("os.remove") diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index b05d7b455..62c2d889e 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -522,7 +522,7 @@ class IsHiddenPathTest(unittest.TestCase): "path_always_hidden", ): path = getattr(self, attr) - with io.open(path, "wt+", encoding="utf-8") as f: + with open(path, "wt+", encoding="utf-8") as f: f.write(attr) if sys.platform == "win32":