py23 compat: using io.open instead of open

for python3 and python2 to work teh same io.open must be used for file handling
This commit is contained in:
MirceaDan committed 2018-11-30 00:32:57 -08:00
1 parent f72f948744
commit 337e49208a
32 files changed
+111 -82

No files matched your search

+2 -1
View File
@@ -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
+3 -2
View File
@@ -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("#")]
+2 -1
View File
@@ -5,6 +5,7 @@ __author__ = "Marc Hannappel <salandora@gmail.com>"
__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:
+2 -1
View File
@@ -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]
+4 -3
View File
@@ -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)
+6 -5
View File
@@ -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):
+3 -2
View File
@@ -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:
+5 -5
View File
@@ -5,7 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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:
+2 -2
View File
@@ -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)
+3 -2
View File
@@ -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)))
+3 -2
View File
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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):
+2 -1
View File
@@ -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
+3 -2
View File
@@ -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
@@ -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:
@@ -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:
@@ -4,6 +4,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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
+3 -2
View File
@@ -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"])
+2 -1
View File
@@ -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
+2 -1
View File
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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:
+2 -1
View File
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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
+4 -3
View File
@@ -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))
+6 -5
View File
@@ -23,6 +23,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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:
+2 -1
View File
@@ -3,6 +3,7 @@ from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__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)
+2 -1
View File
@@ -9,6 +9,7 @@ OctoPrint's source code.
__author__ = "Gina Häußge <osd@foosel.net>"
__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):
+1 -1
View File
@@ -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] != ':':
+2 -1
View File
@@ -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
+3 -1
View File
@@ -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
+2 -2
View File
@@ -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:
+4 -3
View File
@@ -5,6 +5,7 @@ __author__ = "Gina Häußge <osd@foosel.net>"
__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)
+5 -4
View File
@@ -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):
+3 -2
View File
@@ -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":
+19 -18
View File
@@ -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")