Remove workarounds and backports for Python 2 support

In particular:
- In common/, remove the backport of weakref.WeakMethod
- In docs/ and ui/, use the standard FileNotFoundError class
- Use built-in open() instead of io.open(), and stop importing io
- In core/stats.py, use the standard implementation of xml.etree instead
of the C one
This commit is contained in:
Candice Bentéjac 2022-12-05 16:34:01 +01:00
parent 635f85e7fd
commit 8bef398bed
9 changed files with 10 additions and 88 deletions

View file

@ -144,9 +144,8 @@ with multiview.GraphModification(graph):
publish.output.value = args.output
if args.overrides:
import io
import json
with io.open(args.overrides, 'r', encoding='utf-8', errors='ignore') as f:
with open(args.overrides, 'r', encoding='utf-8', errors='ignore') as f:
data = json.load(f)
for nodeName, overrides in data.items():
for attrName, value in overrides.items():

View file

@ -17,12 +17,6 @@ from docutils.nodes import SparseNodeVisitor
from docutils.parsers.rst import Directive
from utils import md_to_docutils, get_link_key
# Python2 compatibility
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
class Relinker(SparseNodeVisitor):

View file

@ -13,59 +13,7 @@ import inspect
import sys
import weakref
from functools import partial
# weakref.WeakMethod backport
try:
from weakref import WeakMethod
except ImportError:
import types
class WeakMethod(object):
"""Light WeakMethod backport compiled from various sources. Tested in 2.7"""
def __init__(self, func):
if inspect.ismethod(func):
self._obj = weakref.ref(func.__self__)
self._func = weakref.ref(func.__func__)
else:
self._obj = None
try:
self._func = weakref.ref(func.__func__)
# Rather than attempting to handle this, raise the same exception
# you get from WeakMethod.
except AttributeError:
raise TypeError("argument should be a bound method, not %s" % type(func))
def __call__(self):
if self._obj is not None:
obj = self._obj()
func = self._func()
if func is None or obj is None:
return None
else:
return types.MethodType(func, obj, obj.__class__)
elif self._func is not None:
return self._func()
else:
return None
def __eq__(self, other):
try:
return type(self) is type(other) and self() == other()
except Exception:
return False
def __ne__(self, other):
return not self.__eq__(other)
from weakref import WeakMethod
class Signal(object):

View file

@ -1,7 +1,7 @@
from meshroom.common import BaseObject, Property, Variant, VariantList, JSValue
from collections.abc import Iterable
from enum import Enum # available by default in python3. For python2: "pip install enum34"
from enum import Enum
import math
import os
import psutil
@ -254,9 +254,7 @@ class IntParam(Param):
def validateValue(self, value):
# handle unsigned int values that are translated to int by shiboken and may overflow
try:
return long(value) # Python 2
except NameError:
return int(value) # Python 3
return int(value)
except:
raise ValueError('IntParam only supports int value (param:{}, value:{}, type:{})'.format(self.name, value, type(value)))

View file

@ -510,8 +510,7 @@ class BaseNode(BaseObject):
def __getattr__(self, k):
try:
# Throws exception if not in prototype chain
# return object.__getattribute__(self, k) # doesn't work in python2
return object.__getattr__(self, k)
return object.__getattribute__(self, k)
except AttributeError as e:
try:
return self.attribute(k)

View file

@ -8,11 +8,7 @@ import platform
import os
import sys
if sys.version_info[0] == 2:
# On Python 2 use C implementation for performance and to avoid lots of warnings
from xml.etree import cElementTree as ET
else:
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET
def bytes2human(n):
@ -95,11 +91,7 @@ class ComputerStatistics:
return
try:
p = subprocess.Popen([self.nvidia_smi, "-q", "-x"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if sys.version_info[0] == 2:
# no timeout in python-2
xmlGpu, stdError = p.communicate()
else:
xmlGpu, stdError = p.communicate(timeout=10) # 10 seconds
xmlGpu, stdError = p.communicate(timeout=10) # 10 seconds
smiTree = ET.fromstring(xmlGpu)
gpuTree = smiTree.find('gpu')

View file

@ -348,7 +348,7 @@ class TaskManager(BaseObject):
raise ValueError("Argument 'context' must be: 'COMPUTATION' or 'SUBMITTING'")
if len(ready) + len(computed) != len(toNodes):
del toNodes[:] # for python 2 compatibility, else use: toNodes.clear()
toNodes.clear()
toNodes.extend(ready)
return False

View file

@ -94,9 +94,8 @@ def readSfMData(sfmFile):
Returns:
The views and intrinsics of the .sfm as two separate lists
"""
import io # use io.open for Python2/3 compatibility (allow to specify encoding + errors handling)
# skip decoding errors to avoid potential exceptions due to non utf-8 characters in images metadata
with io.open(sfmFile, 'r', encoding='utf-8', errors='ignore') as f:
with open(sfmFile, 'r', encoding='utf-8', errors='ignore') as f:
data = json.load(f)
intrinsicsKeys = [i.name for i in Intrinsic]

View file

@ -17,12 +17,6 @@ from meshroom.core.node import Node, CompatibilityNode, Status, Position
from meshroom.ui.graph import UIGraph
from meshroom.ui.utils import makeProperty
# Python2 compatibility
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
class Message(QObject):
""" Simple structure wrapping a high-level message. """
@ -623,9 +617,8 @@ class Reconstruction(UIGraph):
sfmFile = panoramaInit.attribute('outSfMData').value
if not os.path.exists(sfmFile):
return QVector3D(0.0, 0.0, 0.0)
import io # use io.open for Python2/3 compatibility (allow to specify encoding + errors handling)
# skip decoding errors to avoid potential exceptions due to non utf-8 characters in images metadata
with io.open(sfmFile, 'r', encoding='utf-8', errors='ignore') as f:
with open(sfmFile, 'r', encoding='utf-8', errors='ignore') as f:
data = json.load(f)
intrinsics = data.get('intrinsics', [])