Issue #18200: Update the stdlib (except tests) to use

ModuleNotFoundError.
This commit is contained in:
Brett Cannon 2013-06-13 20:57:26 -04:00
parent 9702a17a6a
commit 0a140668fa
83 changed files with 144 additions and 158 deletions

View File

@ -7,7 +7,7 @@ Suggested usage is::
try: try:
import _thread import _thread
except ImportError: except ModuleNotFoundError:
import _dummy_thread as _thread import _dummy_thread as _thread
""" """

View File

@ -62,7 +62,7 @@ def _read_output(commandstring):
try: try:
import tempfile import tempfile
fp = tempfile.NamedTemporaryFile() fp = tempfile.NamedTemporaryFile()
except ImportError: except ModuleNotFoundError:
fp = open("/tmp/_osx_support.%s"%( fp = open("/tmp/_osx_support.%s"%(
os.getpid(),), "w+b") os.getpid(),), "w+b")

View File

@ -9,7 +9,7 @@ import errno
# Import _thread instead of threading to reduce startup cost # Import _thread instead of threading to reduce startup cost
try: try:
from _thread import allocate_lock as Lock from _thread import allocate_lock as Lock
except ImportError: except ModuleNotFoundError:
from _dummy_thread import allocate_lock as Lock from _dummy_thread import allocate_lock as Lock
import io import io
@ -1486,7 +1486,7 @@ class TextIOWrapper(TextIOBase):
if encoding is None: if encoding is None:
try: try:
import locale import locale
except ImportError: except ModuleNotFoundError:
# Importing locale may fail if Python is being built # Importing locale may fail if Python is being built
encoding = "ascii" encoding = "ascii"
else: else:

View File

@ -21,7 +21,7 @@ from datetime import (date as datetime_date,
timezone as datetime_timezone) timezone as datetime_timezone)
try: try:
from _thread import allocate_lock as _thread_allocate_lock from _thread import allocate_lock as _thread_allocate_lock
except ImportError: except ModuleNotFoundError:
from _dummy_thread import allocate_lock as _thread_allocate_lock from _dummy_thread import allocate_lock as _thread_allocate_lock
__all__ = [] __all__ = []

View File

@ -88,5 +88,5 @@ def bisect_left(a, x, lo=0, hi=None):
# Overwrite above definitions with a fast C implementation # Overwrite above definitions with a fast C implementation
try: try:
from _bisect import * from _bisect import *
except ImportError: except ModuleNotFoundError:
pass pass

View File

@ -14,7 +14,7 @@ import warnings
try: try:
from threading import RLock from threading import RLock
except ImportError: except ModuleNotFoundError:
from dummy_threading import RLock from dummy_threading import RLock
from _bz2 import BZ2Compressor, BZ2Decompressor from _bz2 import BZ2Compressor, BZ2Decompressor

View File

@ -109,7 +109,7 @@ class Cmd:
self.old_completer = readline.get_completer() self.old_completer = readline.get_completer()
readline.set_completer(self.complete) readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey+": complete") readline.parse_and_bind(self.completekey+": complete")
except ImportError: except ModuleNotFoundError:
pass pass
try: try:
if intro is not None: if intro is not None:
@ -143,7 +143,7 @@ class Cmd:
try: try:
import readline import readline
readline.set_completer(self.old_completer) readline.set_completer(self.old_completer)
except ImportError: except ModuleNotFoundError:
pass pass

View File

@ -293,7 +293,7 @@ def interact(banner=None, readfunc=None, local=None):
else: else:
try: try:
import readline import readline
except ImportError: except ModuleNotFoundError:
pass pass
console.interact(banner) console.interact(banner)

View File

@ -395,7 +395,7 @@ def _count_elements(mapping, iterable):
try: # Load C helper function if available try: # Load C helper function if available
from _collections import _count_elements from _collections import _count_elements
except ImportError: except ModuleNotFoundError:
pass pass
class Counter(dict): class Counter(dict):

View File

@ -59,7 +59,7 @@ error = Error # backward compatibility
try: try:
from org.python.core import PyStringMap from org.python.core import PyStringMap
except ImportError: except ModuleNotFoundError:
PyStringMap = None PyStringMap = None
__all__ = ["Error", "copy", "deepcopy"] __all__ = ["Error", "copy", "deepcopy"]

View File

@ -2116,7 +2116,7 @@ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
try: try:
from _datetime import * from _datetime import *
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
# Clean up unused names # Clean up unused names

View File

@ -149,7 +149,7 @@ import sys
try: try:
from collections import namedtuple as _namedtuple from collections import namedtuple as _namedtuple
DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
except ImportError: except ModuleNotFoundError:
DecimalTuple = lambda *args: args DecimalTuple = lambda *args: args
# Rounding # Rounding
@ -430,7 +430,7 @@ _rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
# Python was compiled without threads; create a mock object instead # Python was compiled without threads; create a mock object instead
class MockThreading(object): class MockThreading(object):
def local(self, sys=sys): def local(self, sys=sys):
@ -6147,7 +6147,7 @@ del re
# don't care too much if locale isn't present. # don't care too much if locale isn't present.
try: try:
import locale as _locale import locale as _locale
except ImportError: except ModuleNotFoundError:
pass pass
def _parse_format_specifier(format_spec, _localeconv=None): def _parse_format_specifier(format_spec, _localeconv=None):
@ -6391,7 +6391,7 @@ del sys
try: try:
import _decimal import _decimal
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
s1 = set(dir()) s1 = set(dir())

View File

@ -9,7 +9,7 @@ import sys
try: try:
import zipfile import zipfile
except ImportError: except ModuleNotFoundError:
zipfile = None zipfile = None

View File

@ -3,7 +3,7 @@
Contains CCompiler, an abstract base class that defines the interface Contains CCompiler, an abstract base class that defines the interface
for the Distutils compiler abstraction model.""" for the Distutils compiler abstraction model."""
import sys, os, re import importlib, sys, os, re
from distutils.errors import * from distutils.errors import *
from distutils.spawn import spawn from distutils.spawn import spawn
from distutils.file_util import move_file from distutils.file_util import move_file
@ -1013,10 +1013,9 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
try: try:
module_name = "distutils." + module_name module_name = "distutils." + module_name
__import__ (module_name) module = importlib.import_module(module_name)
module = sys.modules[module_name]
klass = vars(module)[class_name] klass = vars(module)[class_name]
except ImportError: except ModuleNotFoundError:
raise DistutilsModuleError( raise DistutilsModuleError(
"can't compile C/C++ code: unable to load module '%s'" % \ "can't compile C/C++ code: unable to load module '%s'" % \
module_name) module_name)

View File

@ -4,11 +4,11 @@ Provides the Distribution class, which represents the module distribution
being built/installed/distributed. being built/installed/distributed.
""" """
import sys, os, re import importlib, sys, os, re
try: try:
import warnings import warnings
except ImportError: except ModuleNotFoundError:
warnings = None warnings = None
from distutils.errors import * from distutils.errors import *
@ -788,9 +788,8 @@ Common commands: (see '--help-commands' for more)
klass_name = command klass_name = command
try: try:
__import__ (module_name) module = importlib.import_module(module_name)
module = sys.modules[module_name] except ModuleNotFoundError:
except ImportError:
continue continue
try: try:

View File

@ -28,7 +28,7 @@ try:
RegEnumValue = winreg.EnumValue RegEnumValue = winreg.EnumValue
RegError = winreg.error RegError = winreg.error
except ImportError: except ModuleNotFoundError:
try: try:
import win32api import win32api
import win32con import win32con
@ -39,7 +39,7 @@ except ImportError:
RegEnumKey = win32api.RegEnumKey RegEnumKey = win32api.RegEnumKey
RegEnumValue = win32api.RegEnumValue RegEnumValue = win32api.RegEnumValue
RegError = win32api.error RegError = win32api.error
except ImportError: except ModuleNotFoundError:
log.info("Warning: Can't read registry to find the " log.info("Warning: Can't read registry to find the "
"necessary compiler setting\n" "necessary compiler setting\n"
"Make sure that Python modules winreg, " "Make sure that Python modules winreg, "

View File

@ -388,7 +388,7 @@ def byte_compile (py_files,
try: try:
from tempfile import mkstemp from tempfile import mkstemp
(script_fd, script_name) = mkstemp(".py") (script_fd, script_name) = mkstemp(".py")
except ImportError: except ModuleNotFoundError:
from tempfile import mktemp from tempfile import mktemp
(script_fd, script_name) = None, mktemp(".py") (script_fd, script_name) = None, mktemp(".py")
log.info("writing byte-compilation script '%s'", script_name) log.info("writing byte-compilation script '%s'", script_name)

View File

@ -29,11 +29,11 @@ Written by Marc-Andre Lemburg (mal@lemburg.com).
"""#" """#"
import codecs import codecs
import importlib
from . import aliases from . import aliases
_cache = {} _cache = {}
_unknown = '--unknown--' _unknown = '--unknown--'
_import_tail = ['*']
_aliases = aliases.aliases _aliases = aliases.aliases
class CodecRegistryError(LookupError, SystemError): class CodecRegistryError(LookupError, SystemError):
@ -94,9 +94,8 @@ def search_function(encoding):
try: try:
# Import is absolute to prevent the possibly malicious import of a # Import is absolute to prevent the possibly malicious import of a
# module with side-effects that is not in the 'encodings' package. # module with side-effects that is not in the 'encodings' package.
mod = __import__('encodings.' + modname, fromlist=_import_tail, mod = importlib.import_module('encodings.' + modname)
level=0) except ModuleNotFoundError:
except ImportError:
pass pass
else: else:
break break

View File

@ -667,7 +667,7 @@ class FTP:
try: try:
import ssl import ssl
except ImportError: except ModuleNotFoundError:
_SSLSocket = None _SSLSocket = None
else: else:
_SSLSocket = ssl.SSLSocket _SSLSocket = ssl.SSLSocket

View File

@ -15,7 +15,7 @@ __all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES',
try: try:
from _functools import reduce from _functools import reduce
except ImportError: except ModuleNotFoundError:
pass pass
from abc import get_cache_token from abc import get_cache_token
from collections import namedtuple from collections import namedtuple
@ -143,7 +143,7 @@ def cmp_to_key(mycmp):
try: try:
from _functools import cmp_to_key from _functools import cmp_to_key
except ImportError: except ModuleNotFoundError:
pass pass
@ -166,7 +166,7 @@ def partial(func, *args, **keywords):
try: try:
from _functools import partial from _functools import partial
except ImportError: except ModuleNotFoundError:
pass pass

View File

@ -36,7 +36,7 @@ __all__ = ["GetoptError","error","getopt","gnu_getopt"]
import os import os
try: try:
from gettext import gettext as _ from gettext import gettext as _
except ImportError: except ModuleNotFoundError:
# Bootstrapping Python: gettext's dependencies not built yet # Bootstrapping Python: gettext's dependencies not built yet
def _(s): return s def _(s): return s

View File

@ -164,7 +164,7 @@ try:
except (ImportError, AttributeError): except (ImportError, AttributeError):
try: try:
import msvcrt import msvcrt
except ImportError: except ModuleNotFoundError:
getpass = fallback_getpass getpass = fallback_getpass
else: else:
getpass = win_getpass getpass = win_getpass

View File

@ -98,7 +98,7 @@ def __get_builtin_constructor(name):
return _sha3.sha3_384 return _sha3.sha3_384
elif bs == '512': elif bs == '512':
return _sha3.sha3_512 return _sha3.sha3_512
except ImportError: except ModuleNotFoundError:
pass # no extension module, this hash is unsupported. pass # no extension module, this hash is unsupported.
raise ValueError('unsupported hash type ' + name) raise ValueError('unsupported hash type ' + name)
@ -143,7 +143,7 @@ try:
__get_hash = __get_openssl_constructor __get_hash = __get_openssl_constructor
algorithms_available = algorithms_available.union( algorithms_available = algorithms_available.union(
_hashlib.openssl_md_meth_names) _hashlib.openssl_md_meth_names)
except ImportError: except ModuleNotFoundError:
new = __py_new new = __py_new
__get_hash = __get_builtin_constructor __get_hash = __get_builtin_constructor

View File

@ -343,7 +343,7 @@ def _siftup_max(heap, pos):
# If available, use C implementation # If available, use C implementation
try: try:
from _heapq import * from _heapq import *
except ImportError: except ModuleNotFoundError:
pass pass
def merge(*iterables): def merge(*iterables):

View File

@ -1156,7 +1156,7 @@ class HTTPConnection:
try: try:
import ssl import ssl
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
class HTTPSConnection(HTTPConnection): class HTTPSConnection(HTTPConnection):

View File

@ -35,7 +35,7 @@ import time
import urllib.parse, urllib.request import urllib.parse, urllib.request
try: try:
import threading as _threading import threading as _threading
except ImportError: except ModuleNotFoundError:
import dummy_threading as _threading import dummy_threading as _threading
import http.client # only for the default HTTP port import http.client # only for the default HTTP port
from calendar import timegm from calendar import timegm

View File

@ -904,7 +904,7 @@ def nobody_uid():
return nobody return nobody
try: try:
import pwd import pwd
except ImportError: except ModuleNotFoundError:
return -1 return -1
try: try:
nobody = pwd.getpwnam('nobody')[2] nobody = pwd.getpwnam('nobody')[2]

View File

@ -29,7 +29,7 @@ from io import DEFAULT_BUFFER_SIZE
try: try:
import ssl import ssl
HAVE_SSL = True HAVE_SSL = True
except ImportError: except ModuleNotFoundError:
HAVE_SSL = False HAVE_SSL = False
__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",

View File

@ -12,7 +12,7 @@ from _imp import (lock_held, acquire_lock, release_lock,
_fix_co_filename) _fix_co_filename)
try: try:
from _imp import load_dynamic from _imp import load_dynamic
except ImportError: except ModuleNotFoundError:
# Platform doesn't support dynamic loading. # Platform doesn't support dynamic loading.
load_dynamic = None load_dynamic = None

View File

@ -14,7 +14,7 @@ import sys
try: try:
import _frozen_importlib as _bootstrap import _frozen_importlib as _bootstrap
except ImportError: except ModuleNotFoundError:
from . import _bootstrap from . import _bootstrap
_bootstrap._setup(sys, _imp) _bootstrap._setup(sys, _imp)
else: else:

View File

@ -3,7 +3,7 @@ from . import _bootstrap
from . import machinery from . import machinery
try: try:
import _frozen_importlib import _frozen_importlib
except ImportError as exc: except ModuleNotFoundError as exc:
if exc.name != '_frozen_importlib': if exc.name != '_frozen_importlib':
raise raise
_frozen_importlib = None _frozen_importlib = None

View File

@ -51,7 +51,7 @@ from collections import namedtuple, OrderedDict
# back to hardcording so the dependency is optional # back to hardcording so the dependency is optional
try: try:
from dis import COMPILER_FLAG_NAMES as _flag_names from dis import COMPILER_FLAG_NAMES as _flag_names
except ImportError: except ModuleNotFoundError:
CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2 CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2
CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8
CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40

View File

@ -5,7 +5,7 @@ import re
from json import scanner from json import scanner
try: try:
from _json import scanstring as c_scanstring from _json import scanstring as c_scanstring
except ImportError: except ModuleNotFoundError:
c_scanstring = None c_scanstring = None
__all__ = ['JSONDecoder'] __all__ = ['JSONDecoder']

View File

@ -4,11 +4,11 @@ import re
try: try:
from _json import encode_basestring_ascii as c_encode_basestring_ascii from _json import encode_basestring_ascii as c_encode_basestring_ascii
except ImportError: except ModuleNotFoundError:
c_encode_basestring_ascii = None c_encode_basestring_ascii = None
try: try:
from _json import make_encoder as c_make_encoder from _json import make_encoder as c_make_encoder
except ImportError: except ModuleNotFoundError:
c_make_encoder = None c_make_encoder = None
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')

View File

@ -3,7 +3,7 @@
import re import re
try: try:
from _json import make_scanner as c_make_scanner from _json import make_scanner as c_make_scanner
except ImportError: except ModuleNotFoundError:
c_make_scanner = None c_make_scanner = None
__all__ = ['make_scanner'] __all__ = ['make_scanner']

View File

@ -706,7 +706,7 @@ class MultiprocessRefactoringTool(RefactoringTool):
items, write, doctests_only) items, write, doctests_only)
try: try:
import multiprocessing import multiprocessing
except ImportError: except ModuleNotFoundError:
raise MultiprocessingUnsupported raise MultiprocessingUnsupported
if self.queue is not None: if self.queue is not None:
raise RuntimeError("already doing multiple processes") raise RuntimeError("already doing multiple processes")

View File

@ -47,7 +47,7 @@ try:
from _locale import * from _locale import *
except ImportError: except ModuleNotFoundError:
# Locale emulation # Locale emulation

View File

@ -37,7 +37,7 @@ __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
try: try:
import threading import threading
except ImportError: #pragma: no cover except ModuleNotFoundError: #pragma: no cover
threading = None threading = None
__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>" __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"

View File

@ -30,7 +30,7 @@ import io
try: try:
import _thread as thread import _thread as thread
import threading import threading
except ImportError: #pragma: no cover except ModuleNotFoundError: #pragma: no cover
thread = None thread = None
from socketserver import ThreadingTCPServer, StreamRequestHandler from socketserver import ThreadingTCPServer, StreamRequestHandler

View File

@ -29,7 +29,7 @@ from stat import ST_DEV, ST_INO, ST_MTIME
import queue import queue
try: try:
import threading import threading
except ImportError: #pragma: no cover except ModuleNotFoundError: #pragma: no cover
threading = None threading = None
# #
@ -995,7 +995,7 @@ class NTEventLogHandler(logging.Handler):
logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
} }
except ImportError: except ModuleNotFoundError:
print("The Python Win32 extensions for NT (service, event "\ print("The Python Win32 extensions for NT (service, event "\
"logging) appear not to be available.") "logging) appear not to be available.")
self._welu = None self._welu = None

View File

@ -187,7 +187,7 @@ def realpath(path):
path = abspath(path) path = abspath(path)
try: try:
import Carbon.File import Carbon.File
except ImportError: except ModuleNotFoundError:
return path return path
if not path: if not path:
return path return path

View File

@ -23,7 +23,7 @@ import io
import contextlib import contextlib
try: try:
import fcntl import fcntl
except ImportError: except ModuleNotFoundError:
fcntl = None fcntl = None
__all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF', __all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',

View File

@ -29,7 +29,7 @@ import posixpath
import urllib.parse import urllib.parse
try: try:
import winreg as _winreg import winreg as _winreg
except ImportError: except ModuleNotFoundError:
_winreg = None _winreg = None
__all__ = [ __all__ = [

View File

@ -27,7 +27,7 @@ from multiprocessing.forking import ForkingPickler
try: try:
import _winapi import _winapi
from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE
except ImportError: except ModuleNotFoundError:
if sys.platform == 'win32': if sys.platform == 'win32':
raise raise
_winapi = None _winapi = None

View File

@ -73,7 +73,7 @@ ForkingPickler.register(type(int.__add__), _reduce_method_descriptor)
try: try:
from functools import partial from functools import partial
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
def _reduce_partial(p): def _reduce_partial(p):

View File

@ -71,7 +71,7 @@ import warnings
try: try:
import ssl import ssl
except ImportError: except ModuleNotFoundError:
_have_ssl = False _have_ssl = False
else: else:
_have_ssl = True _have_ssl = True

View File

@ -566,7 +566,7 @@ def normpath(path):
try: try:
from nt import _getfullpathname from nt import _getfullpathname
except ImportError: # not running on Windows - mock up something sensible except ModuleNotFoundError: # not running on Windows - mock up something sensible
def abspath(path): def abspath(path):
"""Return the absolute version of a path.""" """Return the absolute version of a path."""
if not isabs(path): if not isabs(path):
@ -659,6 +659,6 @@ try:
# This is overkill on Windows - just pass the path to GetFileAttributes # This is overkill on Windows - just pass the path to GetFileAttributes
# and check the attribute from there. # and check the attribute from there.
from nt import _isdir as isdir from nt import _isdir as isdir
except ImportError: except ModuleNotFoundError:
# Use genericpath.isdir as imported above. # Use genericpath.isdir as imported above.
pass pass

View File

@ -360,7 +360,7 @@ def ixor(a, b):
try: try:
from _operator import * from _operator import *
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
from _operator import __doc__ from _operator import __doc__

View File

@ -87,7 +87,7 @@ def _repr(self):
try: try:
from gettext import gettext, ngettext from gettext import gettext, ngettext
except ImportError: except ModuleNotFoundError:
def gettext(message): def gettext(message):
return message return message

View File

@ -52,13 +52,13 @@ if 'posix' in _names:
try: try:
from posix import _exit from posix import _exit
__all__.append('_exit') __all__.append('_exit')
except ImportError: except ModuleNotFoundError:
pass pass
import posixpath as path import posixpath as path
try: try:
from posix import _have_functions from posix import _have_functions
except ImportError: except ModuleNotFoundError:
pass pass
elif 'nt' in _names: elif 'nt' in _names:
@ -68,7 +68,7 @@ elif 'nt' in _names:
try: try:
from nt import _exit from nt import _exit
__all__.append('_exit') __all__.append('_exit')
except ImportError: except ModuleNotFoundError:
pass pass
import ntpath as path import ntpath as path
@ -78,7 +78,7 @@ elif 'nt' in _names:
try: try:
from nt import _have_functions from nt import _have_functions
except ImportError: except ModuleNotFoundError:
pass pass
elif 'ce' in _names: elif 'ce' in _names:
@ -88,7 +88,7 @@ elif 'ce' in _names:
try: try:
from ce import _exit from ce import _exit
__all__.append('_exit') __all__.append('_exit')
except ImportError: except ModuleNotFoundError:
pass pass
# We can use the standard Windows path. # We can use the standard Windows path.
import ntpath as path import ntpath as path
@ -99,11 +99,11 @@ elif 'ce' in _names:
try: try:
from ce import _have_functions from ce import _have_functions
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
raise ImportError('no os specific module found') raise ModuleNotFoundError('no os specific module found')
sys.modules['os.path'] = path sys.modules['os.path'] = path
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,

View File

@ -158,7 +158,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
import readline import readline
# remove some common file name delimiters # remove some common file name delimiters
readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?') readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?')
except ImportError: except ModuleNotFoundError:
pass pass
self.allow_kbdint = False self.allow_kbdint = False
self.nosigint = nosigint self.nosigint = nosigint

View File

@ -90,7 +90,7 @@ class _Stop(Exception):
# Jython has PyStringMap; it's a dict subclass with string keys # Jython has PyStringMap; it's a dict subclass with string keys
try: try:
from org.python.core import PyStringMap from org.python.core import PyStringMap
except ImportError: except ModuleNotFoundError:
PyStringMap = None PyStringMap = None
# Pickle opcodes. See pickletools.py for extensive docs. The listing # Pickle opcodes. See pickletools.py for extensive docs. The listing
@ -1296,7 +1296,7 @@ def loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"):
# Use the faster _pickle if possible # Use the faster _pickle if possible
try: try:
from _pickle import * from _pickle import *
except ImportError: except ModuleNotFoundError:
Pickler, Unpickler = _Pickler, _Unpickler Pickler, Unpickler = _Pickler, _Unpickler
# Doctest # Doctest

View File

@ -460,7 +460,7 @@ def _win32_getvalue(key,name,default=''):
try: try:
# Use win32api if available # Use win32api if available
from win32api import RegQueryValueEx from win32api import RegQueryValueEx
except ImportError: except ModuleNotFoundError:
# On Python 2.0 and later, emulate using winreg # On Python 2.0 and later, emulate using winreg
import winreg import winreg
RegQueryValueEx = winreg.QueryValueEx RegQueryValueEx = winreg.QueryValueEx
@ -503,7 +503,7 @@ def win32_ver(release='',version='',csd='',ptype=''):
RegCloseKey, GetVersionEx RegCloseKey, GetVersionEx
from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \ from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
except ImportError: except ModuleNotFoundError:
# Emulate the win32api module using Python APIs # Emulate the win32api module using Python APIs
try: try:
sys.getwindowsversion sys.getwindowsversion
@ -661,7 +661,7 @@ def _mac_ver_gestalt():
# Check whether the version info module is available # Check whether the version info module is available
try: try:
import _gestalt import _gestalt
except ImportError: except ModuleNotFoundError:
return None return None
# Get the infos # Get the infos
sysv, sysa = _mac_ver_lookup(('sysv','sysa')) sysv, sysa = _mac_ver_lookup(('sysv','sysa'))
@ -697,7 +697,7 @@ def _mac_ver_xml():
try: try:
import plistlib import plistlib
except ImportError: except ModuleNotFoundError:
return None return None
pl = plistlib.readPlist(fn) pl = plistlib.readPlist(fn)
@ -762,7 +762,7 @@ def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
# Import the needed APIs # Import the needed APIs
try: try:
import java.lang import java.lang
except ImportError: except ModuleNotFoundError:
return release,vendor,vminfo,osinfo return release,vendor,vminfo,osinfo
vendor = _java_getprop('java.vendor', vendor) vendor = _java_getprop('java.vendor', vendor)
@ -874,7 +874,7 @@ def _node(default=''):
""" """
try: try:
import socket import socket
except ImportError: except ModuleNotFoundError:
# No sockets... # No sockets...
return default return default
try: try:
@ -1138,7 +1138,7 @@ def uname():
# Get processor information # Get processor information
try: try:
import vms_lib import vms_lib
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0) csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)

View File

@ -20,7 +20,7 @@ import socket
try: try:
import ssl import ssl
HAVE_SSL = True HAVE_SSL = True
except ImportError: except ModuleNotFoundError:
HAVE_SSL = False HAVE_SSL = False
__all__ = ["POP3","error_proto"] __all__ = ["POP3","error_proto"]

View File

@ -528,7 +528,7 @@ if __name__ == '__main__':
import cmd import cmd
try: try:
import readline import readline
except ImportError: except ModuleNotFoundError:
pass pass
class ProfileBrowser(cmd.Cmd): class ProfileBrowser(cmd.Cmd):

View File

@ -67,7 +67,7 @@ def slave_open(tty_name):
result = os.open(tty_name, os.O_RDWR) result = os.open(tty_name, os.O_RDWR)
try: try:
from fcntl import ioctl, I_PUSH from fcntl import ioctl, I_PUSH
except ImportError: except ModuleNotFoundError:
return result return result
try: try:
ioctl(result, I_PUSH, "ptem") ioctl(result, I_PUSH, "ptem")

View File

@ -1893,7 +1893,7 @@ Here is a list of available topics. Enter any topic name to get more help.
def showtopic(self, topic, more_xrefs=''): def showtopic(self, topic, more_xrefs=''):
try: try:
import pydoc_data.topics import pydoc_data.topics
except ImportError: except ModuleNotFoundError:
self.output.write(''' self.output.write('''
Sorry, topic and keyword documentation is not available because the Sorry, topic and keyword documentation is not available because the
module "pydoc_data.topics" could not be found. module "pydoc_data.topics" could not be found.
@ -1933,7 +1933,7 @@ module "pydoc_data.topics" could not be found.
""" """
try: try:
import pydoc_data.topics import pydoc_data.topics
except ImportError: except ModuleNotFoundError:
return(''' return('''
Sorry, topic and keyword documentation is not available because the Sorry, topic and keyword documentation is not available because the
module "pydoc_data.topics" could not be found. module "pydoc_data.topics" could not be found.

View File

@ -2,13 +2,13 @@
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
import dummy_threading as threading import dummy_threading as threading
from collections import deque from collections import deque
from heapq import heappush, heappop from heapq import heappush, heappop
try: try:
from time import monotonic as time from time import monotonic as time
except ImportError: except ModuleNotFoundError:
from time import time from time import time
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue']

View File

@ -13,7 +13,7 @@ EMPTYSTRING = b''
try: try:
from binascii import a2b_qp, b2a_qp from binascii import a2b_qp, b2a_qp
except ImportError: except ModuleNotFoundError:
a2b_qp = None a2b_qp = None
b2a_qp = None b2a_qp = None

View File

@ -6,7 +6,7 @@ import builtins
from itertools import islice from itertools import islice
try: try:
from _thread import get_ident from _thread import get_ident
except ImportError: except ModuleNotFoundError:
from _dummy_thread import get_ident from _dummy_thread import get_ident
def recursive_repr(fillvalue='...'): def recursive_repr(fillvalue='...'):

View File

@ -154,7 +154,7 @@ def get_class_members(klass):
try: try:
import readline import readline
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
readline.set_completer(Completer().complete) readline.set_completer(Completer().complete)

View File

@ -33,11 +33,11 @@ import heapq
from collections import namedtuple from collections import namedtuple
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
import dummy_threading as threading import dummy_threading as threading
try: try:
from time import monotonic as _time from time import monotonic as _time
except ImportError: except ModuleNotFoundError:
from time import time as _time from time import time as _time
__all__ = ["scheduler"] __all__ = ["scheduler"]

View File

@ -17,17 +17,17 @@ try:
import bz2 import bz2
del bz2 del bz2
_BZ2_SUPPORTED = True _BZ2_SUPPORTED = True
except ImportError: except ModuleNotFoundError:
_BZ2_SUPPORTED = False _BZ2_SUPPORTED = False
try: try:
from pwd import getpwnam from pwd import getpwnam
except ImportError: except ModuleNotFoundError:
getpwnam = None getpwnam = None
try: try:
from grp import getgrnam from grp import getgrnam
except ImportError: except ModuleNotFoundError:
getgrnam = None getgrnam = None
__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
@ -668,7 +668,7 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
# command. # command.
try: try:
import zipfile import zipfile
except ImportError: except ModuleNotFoundError:
zipfile = None zipfile = None
if zipfile is None: if zipfile is None:
@ -858,7 +858,7 @@ def _unpack_zipfile(filename, extract_dir):
""" """
try: try:
import zipfile import zipfile
except ImportError: except ModuleNotFoundError:
raise ReadError('zlib not supported, cannot unpack this archive.') raise ReadError('zlib not supported, cannot unpack this archive.')
if not zipfile.is_zipfile(filename): if not zipfile.is_zipfile(filename):

View File

@ -469,7 +469,7 @@ def enablerlcompleter():
try: try:
import readline import readline
import rlcompleter import rlcompleter
except ImportError: except ModuleNotFoundError:
return return
# Reading the initialization (config) file may not be enough to set a # Reading the initialization (config) file may not be enough to set a
@ -570,7 +570,7 @@ def execsitecustomize():
"""Run custom site specific code, if available.""" """Run custom site specific code, if available."""
try: try:
import sitecustomize import sitecustomize
except ImportError: except ModuleNotFoundError:
pass pass
except Exception as err: except Exception as err:
if os.environ.get("PYTHONVERBOSE"): if os.environ.get("PYTHONVERBOSE"):
@ -586,7 +586,7 @@ def execusercustomize():
"""Run custom user specific code, if available.""" """Run custom user specific code, if available."""
try: try:
import usercustomize import usercustomize
except ImportError: except ModuleNotFoundError:
pass pass
except Exception as err: except Exception as err:
if os.environ.get("PYTHONVERBOSE"): if os.environ.get("PYTHONVERBOSE"):

View File

@ -846,7 +846,7 @@ if __name__ == '__main__':
if options.setuid: if options.setuid:
try: try:
import pwd import pwd
except ImportError: except ModuleNotFoundError:
print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr)
sys.exit(1) sys.exit(1)
nobody = pwd.getpwnam('nobody')[2] nobody = pwd.getpwnam('nobody')[2]

View File

@ -171,7 +171,7 @@ def _fix_eols(data):
try: try:
import ssl import ssl
except ImportError: except ModuleNotFoundError:
_have_ssl = False _have_ssl = False
else: else:
_have_ssl = True _have_ssl = True

View File

@ -51,7 +51,7 @@ import os, sys, io
try: try:
import errno import errno
except ImportError: except ModuleNotFoundError:
errno = None errno = None
EBADF = getattr(errno, 'EBADF', 9) EBADF = getattr(errno, 'EBADF', 9)
EAGAIN = getattr(errno, 'EAGAIN', 11) EAGAIN = getattr(errno, 'EAGAIN', 11)

View File

@ -136,7 +136,7 @@ import os
import errno import errno
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
import dummy_threading as threading import dummy_threading as threading
__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",

View File

@ -25,7 +25,7 @@ import unittest
import sqlite3 as sqlite import sqlite3 as sqlite
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
threading = None threading = None
from test.support import TESTFN, unlink from test.support import TESTFN, unlink

View File

@ -26,7 +26,7 @@ import unittest
import sqlite3 as sqlite import sqlite3 as sqlite
try: try:
import zlib import zlib
except ImportError: except ModuleNotFoundError:
zlib = None zlib = None

View File

@ -295,7 +295,7 @@ def _mk_bitmap(bits):
def _optimize_unicode(charset, fixup): def _optimize_unicode(charset, fixup):
try: try:
import array import array
except ImportError: except ModuleNotFoundError:
return charset return charset
charmap = [0]*65536 charmap = [0]*65536
negate = 0 negate = 0

View File

@ -127,14 +127,14 @@ _PROTOCOL_NAMES = {
try: try:
from _ssl import PROTOCOL_SSLv2 from _ssl import PROTOCOL_SSLv2
_SSLv2_IF_EXISTS = PROTOCOL_SSLv2 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
except ImportError: except ModuleNotFoundError:
_SSLv2_IF_EXISTS = None _SSLv2_IF_EXISTS = None
else: else:
_PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2"
try: try:
from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
except ImportError: except ModuleNotFoundError:
pass pass
else: else:
_PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1" _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1"

View File

@ -353,7 +353,7 @@ import warnings
import errno import errno
try: try:
from time import monotonic as _time from time import monotonic as _time
except ImportError: except ModuleNotFoundError:
from time import time as _time from time import time as _time
# Exception classes used by this module. # Exception classes used by this module.

View File

@ -50,7 +50,7 @@ import re
try: try:
import grp, pwd import grp, pwd
except ImportError: except ModuleNotFoundError:
grp = pwd = None grp = pwd = None
# os.symlink on Windows prior to 6.0 raises NotImplementedError # os.symlink on Windows prior to 6.0 raises NotImplementedError
@ -381,7 +381,7 @@ class _Stream:
if comptype == "gz": if comptype == "gz":
try: try:
import zlib import zlib
except ImportError: except ModuleNotFoundError:
raise CompressionError("zlib module is not available") raise CompressionError("zlib module is not available")
self.zlib = zlib self.zlib = zlib
self.crc = zlib.crc32(b"") self.crc = zlib.crc32(b"")
@ -394,7 +394,7 @@ class _Stream:
elif comptype == "bz2": elif comptype == "bz2":
try: try:
import bz2 import bz2
except ImportError: except ModuleNotFoundError:
raise CompressionError("bz2 module is not available") raise CompressionError("bz2 module is not available")
if mode == "r": if mode == "r":
self.dbuf = b"" self.dbuf = b""
@ -406,7 +406,7 @@ class _Stream:
elif comptype == "xz": elif comptype == "xz":
try: try:
import lzma import lzma
except ImportError: except ModuleNotFoundError:
raise CompressionError("lzma module is not available") raise CompressionError("lzma module is not available")
if mode == "r": if mode == "r":
self.dbuf = b"" self.dbuf = b""
@ -1654,7 +1654,7 @@ class TarFile(object):
try: try:
import bz2 import bz2
except ImportError: except ModuleNotFoundError:
raise CompressionError("bz2 module is not available") raise CompressionError("bz2 module is not available")
fileobj = bz2.BZ2File(fileobj or name, mode, fileobj = bz2.BZ2File(fileobj or name, mode,
@ -1678,7 +1678,7 @@ class TarFile(object):
try: try:
import lzma import lzma
except ImportError: except ModuleNotFoundError:
raise CompressionError("lzma module is not available") raise CompressionError("lzma module is not available")
fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset) fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset)

View File

@ -36,7 +36,7 @@ from random import Random as _Random
try: try:
import fcntl as _fcntl import fcntl as _fcntl
except ImportError: except ModuleNotFoundError:
def _set_cloexec(fd): def _set_cloexec(fd):
pass pass
else: else:
@ -53,7 +53,7 @@ else:
try: try:
import _thread import _thread
except ImportError: except ModuleNotFoundError:
import _dummy_thread as _thread import _dummy_thread as _thread
_allocate_lock = _thread.allocate_lock _allocate_lock = _thread.allocate_lock

View File

@ -6,14 +6,14 @@ import _thread
from time import sleep as _sleep from time import sleep as _sleep
try: try:
from time import monotonic as _time from time import monotonic as _time
except ImportError: except ModuleNotFoundError:
from time import time as _time from time import time as _time
from traceback import format_exc as _format_exc from traceback import format_exc as _format_exc
from _weakrefset import WeakSet from _weakrefset import WeakSet
from itertools import islice as _islice from itertools import islice as _islice
try: try:
from _collections import deque as _deque from _collections import deque as _deque
except ImportError: except ModuleNotFoundError:
from collections import deque as _deque from collections import deque as _deque
# Note regarding PEP 8 compliant names # Note regarding PEP 8 compliant names
@ -922,7 +922,7 @@ _shutdown = _MainThread()._exitfunc
try: try:
from _thread import _local as local from _thread import _local as local
except ImportError: except ModuleNotFoundError:
from _threading_local import local from _threading_local import local

View File

@ -61,12 +61,12 @@ import pickle
from warnings import warn as _warn from warnings import warn as _warn
try: try:
from time import monotonic as _time from time import monotonic as _time
except ImportError: except ModuleNotFoundError:
from time import time as _time from time import time as _time
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
_settrace = sys.settrace _settrace = sys.settrace
def _unsettrace(): def _unsettrace():

View File

@ -110,7 +110,7 @@ from urllib.response import addinfourl, addclosehook
# check for SSL # check for SSL
try: try:
import ssl import ssl
except ImportError: except ModuleNotFoundError:
_have_ssl = False _have_ssl = False
else: else:
_have_ssl = True _have_ssl = True
@ -2512,7 +2512,7 @@ elif os.name == 'nt':
proxies = {} proxies = {}
try: try:
import winreg import winreg
except ImportError: except ModuleNotFoundError:
# Std module, so should be around - but you never know! # Std module, so should be around - but you never know!
return proxies return proxies
try: try:
@ -2560,7 +2560,7 @@ elif os.name == 'nt':
def proxy_bypass_registry(host): def proxy_bypass_registry(host):
try: try:
import winreg import winreg
except ImportError: except ModuleNotFoundError:
# Std modules, so should be around - but you never know! # Std modules, so should be around - but you never know!
return 0 return 0
try: try:

View File

@ -35,7 +35,7 @@ import sys
import sysconfig import sysconfig
try: try:
import threading import threading
except ImportError: except ModuleNotFoundError:
threading = None threading = None
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

View File

@ -144,8 +144,8 @@ def _getcategory(category):
module = category[:i] module = category[:i]
klass = category[i+1:] klass = category[i+1:]
try: try:
m = __import__(module, None, None, [klass]) m = __import__(module, fromlist[klass])
except ImportError: except ModuleNotFoundError:
raise _OptionError("invalid module name: %r" % (module,)) raise _OptionError("invalid module name: %r" % (module,))
try: try:
cat = getattr(m, klass) cat = getattr(m, klass)
@ -362,7 +362,7 @@ try:
defaultaction = _defaultaction defaultaction = _defaultaction
onceregistry = _onceregistry onceregistry = _onceregistry
_warnings_defaults = True _warnings_defaults = True
except ImportError: except ModuleNotFoundError:
filters = [] filters = []
defaultaction = "default" defaultaction = "default"
onceregistry = {} onceregistry = {}

View File

@ -1439,13 +1439,13 @@ class XMLParser:
def __init__(self, html=0, target=None, encoding=None): def __init__(self, html=0, target=None, encoding=None):
try: try:
from xml.parsers import expat from xml.parsers import expat
except ImportError: except ModuleNotFoundError:
try: try:
import pyexpat as expat import pyexpat as expat
except ImportError: except ModuleNotFoundError:
raise ImportError( raise ModuleNotFoundError(
"No module named expat; use SimpleXMLTreeBuilder instead" "No module named expat; use SimpleXMLTreeBuilder instead",
) name='expat')
parser = expat.ParserCreate(encoding, "}") parser = expat.ParserCreate(encoding, "}")
if target is None: if target is None:
target = TreeBuilder() target = TreeBuilder()

View File

@ -20,7 +20,7 @@ del sys
try: try:
from xml.parsers import expat from xml.parsers import expat
except ImportError: except ModuleNotFoundError:
raise SAXReaderNotAvailable("expat not supported", None) raise SAXReaderNotAvailable("expat not supported", None)
else: else:
if not hasattr(expat, "ParserCreate"): if not hasattr(expat, "ParserCreate"):
@ -30,18 +30,7 @@ from xml.sax import xmlreader, saxutils, handler
AttributesImpl = xmlreader.AttributesImpl AttributesImpl = xmlreader.AttributesImpl
AttributesNSImpl = xmlreader.AttributesNSImpl AttributesNSImpl = xmlreader.AttributesNSImpl
# If we're using a sufficiently recent version of Python, we can use import weakref
# weak references to avoid cycles between the parser and content
# handler, otherwise we'll just have to pretend.
try:
import _weakref
except ImportError:
def _mkproxy(o):
return o
else:
import weakref
_mkproxy = weakref.proxy
del weakref, _weakref
# --- ExpatLocator # --- ExpatLocator
@ -52,7 +41,7 @@ class ExpatLocator(xmlreader.Locator):
a circular reference between the parser and the content handler. a circular reference between the parser and the content handler.
""" """
def __init__(self, parser): def __init__(self, parser):
self._ref = _mkproxy(parser) self._ref = weakref.proxy(parser)
def getColumnNumber(self): def getColumnNumber(self):
parser = self._ref parser = self._ref

View File

@ -139,7 +139,7 @@ import errno
from io import BytesIO from io import BytesIO
try: try:
import gzip import gzip
except ImportError: except ModuleNotFoundError:
gzip = None #python can be built without zlib/gzip support gzip = None #python can be built without zlib/gzip support
# -------------------------------------------------------------------- # --------------------------------------------------------------------