From 337e49208acd3f3c0ae3723ef9119852d8e1100a Mon Sep 17 00:00:00 2001 From: MirceaDan Date: Fri, 30 Nov 2018 00:32:57 -0800 Subject: [PATCH] py23 compat: using io.open instead of open for python3 and python2 to work teh same io.open must be used for file handling --- src/octoprint/__init__.py | 3 +- src/octoprint/_version.py | 5 ++- src/octoprint/access/groups.py | 3 +- src/octoprint/access/users.py | 3 +- src/octoprint/cli/client.py | 7 ++-- src/octoprint/daemon.py | 11 +++--- src/octoprint/filemanager/__init__.py | 5 ++- src/octoprint/filemanager/storage.py | 10 ++--- src/octoprint/filemanager/util.py | 4 +- src/octoprint/plugin/core.py | 5 ++- src/octoprint/plugins/cura/__init__.py | 5 ++- src/octoprint/plugins/logging/__init__.py | 3 +- src/octoprint/plugins/pi_support/__init__.py | 5 ++- .../plugins/pluginmanager/__init__.py | 7 ++-- .../plugins/softwareupdate/__init__.py | 3 +- .../plugins/virtual_printer/virtual.py | 5 ++- src/octoprint/printer/profile.py | 5 ++- src/octoprint/server/__init__.py | 3 +- src/octoprint/server/api/__init__.py | 3 +- src/octoprint/server/api/languages.py | 3 +- src/octoprint/server/util/flask.py | 7 ++-- src/octoprint/settings.py | 11 +++--- src/octoprint/timelapse.py | 3 +- src/octoprint/util/__init__.py | 3 +- src/octoprint/util/avr_isp/intelHex.py | 2 +- src/octoprint/util/pip.py | 3 +- src/octoprint/util/piptestballoon/setup.py | 4 +- src/octoprint_client/__init__.py | 4 +- tests/filemanager/test_localstorage.py | 7 ++-- tests/settings/test_settings.py | 9 +++-- tests/util/test_file_helpers.py | 5 ++- versioneer.py | 37 ++++++++++--------- 32 files changed, 111 insertions(+), 82 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 3ee4ed588..10ca2bc33 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -2,6 +2,7 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function +import io import sys import logging as log @@ -293,7 +294,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with open(logging_file, "r") as f: + with io.open(logging_file, 'rb') as f: config_from_file = yaml.safe_load(f) # we merge that with the default config diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index a08e11a97..9616fb06b 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -12,6 +12,7 @@ from __future__ import absolute_import, division, print_function import errno +import io import os import re import subprocess @@ -130,7 +131,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") + f = io.open(versionfile_abs, 'rb') for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -306,7 +307,7 @@ def git_parse_lookup_file(path): return [] lookup = [] - with open(path, "r") as f: + with io.open(path, 'rb') as f: for line in f: if '#' in line: line = line[:line.rindex("#")] diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 8b2f02c66..fa87cd884 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -5,6 +5,7 @@ __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,7 +184,7 @@ class FilebasedGroupManager(GroupManager): def _load(self): if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile): try: - with open(self._groupfile, "r") as f: + with io.open(self._groupfile, 'rb') as f: data = yaml.safe_load(f) if not "groups" in data: diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 54ee6ec00..8fbc15107 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from flask_login import UserMixin, AnonymousUserMixin from werkzeug.local import LocalProxy import hashlib +import io import os import yaml import uuid @@ -432,7 +433,7 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): self._customized = True - with open(self._userfile, "r") as f: + with io.open(self._userfile, 'rb') as f: data = yaml.safe_load(f) for name in data.keys(): attributes = data[name] diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index b40f710c3..d8a7c79cb 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -5,6 +5,7 @@ __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 click +import io import json import octoprint_client @@ -143,16 +144,16 @@ 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 open(file_path, "rb") as fp: + with io.open(file_path, 'rb') as fp: data = json.load(fp) else: import yaml - with open(file_path, "rb") as fp: + with io.open(file_path, 'rb') as fp: data = yaml.safe_load(fp) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: - with open(file_path, "rb") as fp: + with io.open(file_path, 'rb') as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 6b42e1d88..9c230d5e9 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -6,6 +6,7 @@ Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon """ from __future__ import absolute_import, division, print_function +import io import sys, os, time, signal class Daemon: @@ -60,9 +61,9 @@ class Daemon: # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() - si = open(os.devnull, 'r') - so = open(os.devnull, 'a+') - se = open(os.devnull, 'a+') + si = io.open(os.devnull, 'rb') + so = io.open(os.devnull, 'a+') + se = io.open(os.devnull, 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) @@ -142,7 +143,7 @@ class Daemon: def get_pid(self): """Get the pid from the pidfile.""" try: - with open(self.pidfile,'r') as pf: + with io.open(self.pidfile,'rb') as pf: pid = int(pf.read().strip()) except (IOError, ValueError): pid = None @@ -150,7 +151,7 @@ class Daemon: def set_pid(self, pid): """Write the pid to the pidfile.""" - with open(self.pidfile,'w+') as f: + with io.open(self.pidfile,'wb+') as f: f.write(str(pid) + '\n') def remove_pidfile(self): diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index df179d1ee..a0e54a60b 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -6,6 +6,7 @@ __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 logging +import io import os import octoprint.plugin @@ -338,7 +339,7 @@ class FileManager(object): _, stl_name = self.split_path(source_location, source_path) file_obj = StreamWrapper(os.path.basename(dest_path), io.BytesIO(u";Generated from {stl_name} {hash}\n".format(**locals()).encode("ascii", "replace")), - io.FileIO(tmp_path, "rb")) + io.FileIO(tmp_path, 'rb')) printer_profile = self._printer_profile_manager.get(printer_profile_id) self.add_file(dest_location, dest_path, file_obj, @@ -642,7 +643,7 @@ class FileManager(object): import yaml try: - with open(self._recovery_file) as f: + with io.open(self._recovery_file, 'rb') as f: data = yaml.safe_load(f) return data except: diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 9cafb0811..392c5ea6c 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -5,7 +5,7 @@ __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 import os import pylru @@ -500,7 +500,7 @@ class LocalFileStorage(StorageInterface): if os.path.exists(old_metadata_path): # load the old metadata file try: - with open(old_metadata_path) as f: + with io.open(old_metadata_path, 'rb') as f: import yaml self._old_metadata = yaml.safe_load(f) except: @@ -1462,7 +1462,7 @@ class LocalFileStorage(StorageInterface): blocksize = 65536 hash = hashlib.sha1() - with open(path, "rb") as f: + with io.open(path, 'rb') as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -1522,7 +1522,7 @@ class LocalFileStorage(StorageInterface): metadata_path = os.path.join(path, ".metadata.json") if os.path.exists(metadata_path): - with open(metadata_path) as f: + with io.open(metadata_path, 'rb') as f: try: import json metadata = json.load(f) @@ -1577,7 +1577,7 @@ class LocalFileStorage(StorageInterface): # TODO 1.3.10 Remove ".metadata.yaml" files return - with open(metadata_path_yaml) as f: + with io.open(metadata_path_yaml, 'rb') as f: try: metadata = yaml.safe_load(f) except: diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index d8bd9561f..5bbadd063 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -64,7 +64,7 @@ class DiskFileWrapper(AbstractFileWrapper): shutil.copy2(self.path, path) def stream(self): - return io.open(self.path, "rb") + return io.open(self.path, 'rb') class StreamWrapper(AbstractFileWrapper): """ @@ -87,7 +87,7 @@ class StreamWrapper(AbstractFileWrapper): """ import shutil - with atomic_write(path, "wb") as dest: + with atomic_write(path, 'wb') as dest: with self.stream() as source: shutil.copyfileobj(source, dest) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 79240bff7..e9de9e726 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -28,6 +28,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import os +import io import imp from collections import defaultdict, namedtuple, OrderedDict import logging @@ -512,7 +513,7 @@ class PluginInfo(object): try: import ast - with open(path, "rb") as f: + with io.open(path, 'rb') as f: root = ast.parse(f.read()) assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets, @@ -1619,7 +1620,7 @@ def is_editable_install(install_dir, package, module, location): if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: - with open(package_link) as f: + with io.open(package_link, 'rb') as f: contents = f.readlines() for line in contents: target = os.path.normcase(os.path.realpath(os.path.join(line.strip(), module))) diff --git a/src/octoprint/plugins/cura/__init__.py b/src/octoprint/plugins/cura/__init__.py index ef736673c..a6d9b8e14 100644 --- a/src/octoprint/plugins/cura/__init__.py +++ b/src/octoprint/plugins/cura/__init__.py @@ -5,6 +5,7 @@ __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 import logging.handlers import os @@ -459,7 +460,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, def _load_profile(self, path): import yaml profile_dict = dict() - with open(path, "r") as f: + with io.open(path, 'rb') as f: try: profile_dict = yaml.safe_load(f) except: @@ -473,7 +474,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin, def _save_profile(self, path, profile, allow_overwrite=True): import yaml - with octoprint.util.atomic_write(path, "wb", max_permissions=0o666) as f: + with octoprint.util.atomic_write(path, 'wb', max_permissions=0o666) as f: yaml.safe_dump(profile, f, default_flow_style=False, indent=2, allow_unicode=True) def _convert_to_engine(self, profile_path, printer_profile, pos_x=None, pos_y=None, used_extruders=1): diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 7ae1108e6..92b602e17 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -18,6 +18,7 @@ from werkzeug.utils import secure_filename from werkzeug.exceptions import BadRequest import yaml +import io import os try: @@ -145,7 +146,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin, config_from_file = {} if os.path.exists(logging_file) and os.path.isfile(logging_file): import yaml - with open(logging_file, "r") as f: + with io.open(logging_file, 'rb') as f: config_from_file = yaml.safe_load(f) return config_from_file diff --git a/src/octoprint/plugins/pi_support/__init__.py b/src/octoprint/plugins/pi_support/__init__.py index e0bd9ac10..24faba68e 100644 --- a/src/octoprint/plugins/pi_support/__init__.py +++ b/src/octoprint/plugins/pi_support/__init__.py @@ -5,6 +5,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import flask +import io import os import sarge @@ -124,7 +125,7 @@ def get_proc_dt_model(): global _proc_dt_model if _proc_dt_model is None: - with open(_PROC_DT_MODEL_PATH, "r") as f: + with io.open(_PROC_DT_MODEL_PATH, 'rb') as f: _proc_dt_model = f.readline().strip(" \t\r\n\0") return _proc_dt_model @@ -150,7 +151,7 @@ def get_octopi_version(): global _octopi_version if _octopi_version is None: - with open(_OCTOPI_VERSION_PATH, "r") as f: + with io.open(_OCTOPI_VERSION_PATH, 'rb') as f: _octopi_version = f.readline().strip(" \t\r\n\0") return _octopi_version diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 41cb6d004..c87d83e7f 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -20,6 +20,7 @@ from octoprint.util.platform import get_os from flask import jsonify, make_response from flask_babel import gettext +import io import logging import sarge import sys @@ -758,7 +759,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if mtime + self._repository_cache_ttl >= time.time() > mtime: try: import json - with open(self._repository_cache_path) as f: + with io.open(self._repository_cache_path, 'rb') as f: repo_data = json.load(f) self._logger.info("Loaded plugin repository data from disk, was still valid") except: @@ -784,7 +785,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, try: import json - with octoprint.util.atomic_write(self._repository_cache_path, "wb") as f: + with octoprint.util.atomic_write(self._repository_cache_path, 'wb') as f: json.dump(repo_data, f) except Exception as e: self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e))) @@ -832,7 +833,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if mtime + self._notices_cache_ttl >= time.time() > mtime: try: import json - with open(self._notices_cache_path) as f: + with io.open(self._notices_cache_path, 'rb') as f: notice_data = json.load(f) self._logger.info("Loaded notice data from disk, was still valid") except: diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index e9293e6a8..473b47115 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import octoprint.plugin +import io import copy import flask import os @@ -187,7 +188,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, import yaml try: - with open(self._version_cache_path) as f: + with io.open(self._version_cache_path, 'rb') as f: data = yaml.safe_load(f) timestamp = os.stat(self._version_cache_path).st_mtime except: diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 3d9ada889..6e7a28640 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -4,6 +4,7 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +import io import time import os import re @@ -1106,7 +1107,7 @@ class VirtualPrinter(object): handle = None try: - handle = open(file, "w") + handle = io.open(file, 'wb') except: self._output("error writing to file") if handle is not None: @@ -1133,7 +1134,7 @@ class VirtualPrinter(object): def _sdPrintingWorker(self): self._selectedSdFilePos = 0 try: - with open(self._selectedSdFile, "r") as f: + with io.open(self._selectedSdFile, 'rb') as f: for line in iter(f.readline, ""): if self._killed or not self._sdPrinting: break diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index 0a021c471..2363101f2 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -144,6 +144,7 @@ __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 io import os import copy import re @@ -430,7 +431,7 @@ class PrinterProfileManager(object): return None import yaml - with open(path) as f: + with io.open(path, 'rb') as f: profile = yaml.safe_load(f) if profile is None or not isinstance(profile, dict): @@ -460,7 +461,7 @@ class PrinterProfileManager(object): from octoprint.util import atomic_write import yaml try: - with atomic_write(path, "wb", max_permissions=0o666) as f: + with atomic_write(path, 'wb', max_permissions=0o666) as f: yaml.safe_dump(profile, f, default_flow_style=False, indent=2, allow_unicode=True) except Exception as e: self._logger.exception("Error while trying to save profile %s" % profile["id"]) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 32ec54ac4..ec1fcf741 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -26,6 +26,7 @@ import octoprint.util.net from octoprint.server import util from octoprint.util.json import JsonEncoding +import io import os import logging import logging.config @@ -1600,7 +1601,7 @@ class Server(object): if not os.path.isfile(path): return "" - with open(path, "rb") as f: + with io.open(path, 'rb') as f: data = f.read() return data diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 6abf081a5..12e4acce7 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -5,6 +5,7 @@ __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 Blueprint, request, jsonify, abort, current_app, session, make_response, g @@ -331,7 +332,7 @@ def _test_path(data): if check_writable_dir and check_type == "dir": try: test_path = os.path.join(path, ".testballoon.txt") - with open(test_path, "wb") as f: + with io.open(test_path, 'wb') as f: f.write("Test") os.remove(test_path) except: diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 9d76ea6e1..4eab898d2 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -5,6 +5,7 @@ __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 os import tarfile import zipfile @@ -49,7 +50,7 @@ def getInstalledLanguagePacks(): if os.path.isfile(meta_path): import yaml try: - with open(meta_path) as f: + with io.open(meta_path, 'rb') as f: meta = yaml.safe_load(f) except: pass diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index abc9a13f3..a6c02f7a5 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -13,6 +13,7 @@ import flask.json import flask_login import flask_principal import flask_assets +import io import webassets.updater import webassets.utils import functools @@ -189,7 +190,7 @@ def fix_webassets_cache(): filename = os.path.join(self.directory, '%s' % hash) try: - f = open(filename, 'rb') + f = io.open(filename, 'rb') except IOError as e: if e.errno != errno.ENOENT: error_logger.exception("Got an exception while trying to open webasset file {}".format(filename)) @@ -808,7 +809,7 @@ class PreemptiveCache(object): cache_data = None with self._lock: try: - with open(self.cachefile, "r") as f: + with io.open(self.cachefile, 'rb') as f: cache_data = yaml.safe_load(f) except IOError as e: import errno @@ -832,7 +833,7 @@ class PreemptiveCache(object): with self._lock: try: - with atomic_write(self.cachefile, "wb", max_permissions=0o666) as handle: + with atomic_write(self.cachefile, 'wb', max_permissions=0o666) as handle: yaml.safe_dump(data, handle,default_flow_style=False, indent=4, allow_unicode=True) except: self._logger.exception("Error while writing {}".format(self.cachefile)) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index fe8c50fcc..301042129 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -23,6 +23,7 @@ __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 sys import os import yaml @@ -867,7 +868,7 @@ class Settings(object): def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): - with open(self._configfile, "r") as f: + with io.open(self._configfile, 'rb') as f: try: self._config = yaml.safe_load(f) self._mtime = self.last_modified @@ -906,7 +907,7 @@ class Settings(object): if isinstance(overlay, basestring): if os.path.exists(overlay) and os.path.isfile(overlay): - with open(overlay, "r") as f: + with io.open(overlay, 'rb') as f: config = yaml.safe_load(f) elif isinstance(overlay, dict): config = overlay @@ -1319,7 +1320,7 @@ class Settings(object): from octoprint.util import atomic_write try: - with atomic_write(self._configfile, "wb", prefix="octoprint-config-", suffix=".yaml", permissions=0o600, max_permissions=0o666) as configFile: + with atomic_write(self._configfile, 'wb', prefix="octoprint-config-", suffix=".yaml", permissions=0o600, max_permissions=0o666) as configFile: yaml.safe_dump(self._config, configFile, default_flow_style=False, indent=4, allow_unicode=True) self._dirty = False except: @@ -1733,7 +1734,7 @@ class Settings(object): path, _ = os.path.split(filename) if not os.path.exists(path): os.makedirs(path) - with atomic_write(filename, "wb", max_permissions=0o666) as f: + with atomic_write(filename, 'wb', max_permissions=0o666) as f: f.write(script) def generateApiKey(self): @@ -1794,7 +1795,7 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab # to determine whether things are *actually* writable testfile = os.path.join(folder, ".testballoon.txt") try: - with open(testfile, "wb") as f: + with io.open(testfile, 'wb') as f: f.write("test") os.remove(testfile) except: diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 4d7810c79..0c6b78bc5 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -3,6 +3,7 @@ from __future__ import absolute_import, division, print_function __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +import io import logging import os import threading @@ -646,7 +647,7 @@ class Timelapse(object): verify=self._snapshot_validate_ssl) r.raise_for_status() - with open (filename, "wb") as f: + with io.open(filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 912f197a7..6fbb8a6a1 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -9,6 +9,7 @@ OctoPrint's source code. __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +import io import os import traceback import past.builtins @@ -1005,7 +1006,7 @@ 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 open(filename, "rb") as f: + with io.open(filename, 'rb') as f: header = f.read(4) if header.startswith(bom): diff --git a/src/octoprint/util/avr_isp/intelHex.py b/src/octoprint/util/avr_isp/intelHex.py index 616038c05..85b893de3 100644 --- a/src/octoprint/util/avr_isp/intelHex.py +++ b/src/octoprint/util/avr_isp/intelHex.py @@ -5,7 +5,7 @@ from builtins import range def readHex(filename): data = [] extraAddr = 0 - f = io.open(filename, "r") + f = io.open(filename, 'rb') for line in f: line = line.strip() if line[0] != ':': diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py index 87ccdb7e3..9fcb958a4 100644 --- a/src/octoprint/util/pip.py +++ b/src/octoprint/util/pip.py @@ -6,6 +6,7 @@ __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 io import sarge import sys import logging @@ -369,7 +370,7 @@ class PipCaller(CommandlineCaller): return False, False, False, None data = dict() - with open(testballoon_output_file) as f: + with io.open(testballoon_output_file, 'rb') as f: for line in f: key, value = line.split("=", 2) data[key] = value diff --git a/src/octoprint/util/piptestballoon/setup.py b/src/octoprint/util/piptestballoon/setup.py index fa20dff22..a884181a3 100644 --- a/src/octoprint/util/piptestballoon/setup.py +++ b/src/octoprint/util/piptestballoon/setup.py @@ -1,4 +1,6 @@ from __future__ import absolute_import, division, print_function + +import io import os import sys @@ -38,7 +40,7 @@ path = os.environ.get("TESTBALLOON_OUTPUT", None) if path is not None: # environment variable set, write to a log path = os.path.abspath(path) - with open(path, mode="w+b") as output: + with io.open(path, 'w+b') as output: produce_output(output) else: # write to stdout diff --git a/src/octoprint_client/__init__.py b/src/octoprint_client/__init__.py index 49adb5618..8d43befae 100644 --- a/src/octoprint_client/__init__.py +++ b/src/octoprint_client/__init__.py @@ -4,7 +4,7 @@ from __future__ import absolute_import, division, print_function __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 requests import time @@ -261,7 +261,7 @@ class Client(object): if file_name is None: file_name = os.path.basename(file_path) - with open(file_path, "rb") as fp: + with io.open(file_path, 'rb') as fp: if content_type: files = dict(file=(file_name, fp, content_type)) else: diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index 491608f1a..e6459bda7 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -5,6 +5,7 @@ __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 unittest import os import mock @@ -22,7 +23,7 @@ class FileWrapper(object): import hashlib blocksize = 65536 hash = hashlib.sha1() - with open(self.path, "rb") as f: + with io.open(self.path, 'rb') as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -652,7 +653,7 @@ class LocalStorageTest(unittest.TestCase): # prepare import yaml - with open(yaml_path, "wb") as f: + with io.open(yaml_path, 'wb') as f: yaml.safe_dump(metadata, f) # migrate @@ -663,7 +664,7 @@ class LocalStorageTest(unittest.TestCase): self.assertTrue(os.path.exists(yaml_path)) # TODO 1.3.10 change to assertFalse import json - with open(json_path) as f: + with io.open(json_path, 'rb') as f: json_metadata = json.load(f) self.assertDictEqual(metadata, json_metadata) diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 39d6570b1..d96acec9b 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -9,6 +9,7 @@ Tests for OctoPrint's Settings class * tests for settings migration """ +import io import unittest import shutil import contextlib @@ -27,18 +28,18 @@ class TestSettings(unittest.TestCase): def _load_yaml(self, fname): if sys.version_info[0] >= 3: - with open(fname, "r+", encoding='utf-8') as f: + with io.open(fname, 'r+b', encoding='utf-8') as f: return yaml.safe_load(f) else: - with open(fname, "r+b") as f: + with io.open(fname, 'r+b') as f: return yaml.safe_load(f) def _dump_yaml(self, fname, config): if sys.version_info[0] >= 3: - with open(fname, "w+", encoding='utf-8') as f: + with io.open(fname, 'w+', encoding='utf-8') as f: yaml.safe_dump(config, f) else: - with open(fname, "wb+") as f: + with io.open(fname, 'wb+') as f: yaml.safe_dump(config, f) def setUp(self): diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 214424891..9c2e38374 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -4,6 +4,7 @@ from __future__ import absolute_import, division, print_function __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 unittest import mock import os @@ -336,10 +337,10 @@ class IsHiddenPathTest(unittest.TestCase): for attr in ("path_always_visible", "path_hidden_on_windows", "path_always_hidden"): path = getattr(self, attr) if sys.version_info[0] >= 3: - with open(path, "w+", encoding='utf-8') as f: + with io.open(path, 'w+b', encoding='utf-8') as f: f.write(attr) else: - with open(path, "wb+") as f: + with io.open(path, 'wb+') as f: f.write(attr) if sys.platform == "win32": diff --git a/versioneer.py b/versioneer.py index dcb7bd0f1..9bf381bcf 100644 --- a/versioneer.py +++ b/versioneer.py @@ -375,6 +375,7 @@ try: except ImportError: import ConfigParser as configparser import errno +import io import json import os import re @@ -427,7 +428,7 @@ def get_config_from_root(root): # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() - with open(setup_cfg, "r") as f: + with io.open(setup_cfg, 'rb') as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory @@ -629,7 +630,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") + f = io.open(versionfile_abs, 'rb') for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -806,7 +807,7 @@ def git_parse_lookup_file(path): import re lookup = [] - with open(path, "r") as f: + with io.open(path, 'rb') as f: for line in f: if '#' in line: line = line[:line.index("#")] @@ -1201,7 +1202,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs, "r") + f = io.open(versionfile_abs, 'rt') for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -1378,7 +1379,7 @@ def git_parse_lookup_file(path): import re lookup = [] - with open(path, "r") as f: + with io.open(path, 'rb') as f: for line in f: if '#' in line: line = line[:line.index("#")] @@ -1501,7 +1502,7 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): files.append(versioneer_file) present = False try: - f = open(".gitattributes", "r") + f = io.open('.gitattributes', 'rt') for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: @@ -1510,7 +1511,7 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): except EnvironmentError: pass if not present: - f = open(".gitattributes", "a+") + f = io.open('.gitattributes', 'a+') f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") @@ -1554,7 +1555,7 @@ def get_versions(): def versions_from_file(filename): try: - with open(filename) as f: + with io.open(filename, 'rb') as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") @@ -1569,7 +1570,7 @@ def write_to_version_file(filename, versions): os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) - with open(filename, "w") as f: + with io.open(filename, 'wb') as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) @@ -1982,7 +1983,7 @@ def get_cmdclass(): _build_exe.run(self) os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: + with io.open(cfg.versionfile_source, 'wb') as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", @@ -2079,13 +2080,13 @@ def do_setup(): if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: + with io.open(os.path.join(root, "setup.cfg"), 'a') as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: + with io.open(cfg.versionfile_source, 'wb') as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, @@ -2099,13 +2100,13 @@ def do_setup(): "__init__.py") if os.path.exists(ipy): try: - with open(ipy, "r") as f: + with io.open(ipy, 'rb') as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) - with open(ipy, "a") as f: + with io.open(ipy, 'a') as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) @@ -2120,7 +2121,7 @@ def do_setup(): manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: - with open(manifest_in, "r") as f: + with io.open(manifest_in, 'rb') as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: @@ -2133,14 +2134,14 @@ def do_setup(): # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: + with io.open(manifest_in, 'a') as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) - with open(manifest_in, "a") as f: + with io.open(manifest_in, 'a') as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") @@ -2156,7 +2157,7 @@ def scan_setup_py(): found = set() setters = False errors = 0 - with open("setup.py", "r") as f: + with io.open("setup.py", 'rb') as f: for line in f.readlines(): if "import versioneer" in line: found.add("import")