[Build] print_python_deps.py: Use importlib.util for Python 3.

This CL removes the warning message
  DeprecationWarning: the imp module is deprecated...

from running print_python_deps.py on SuperSize (or other Python 3
projects). The key is to follow the recommendation to use importlib.
Caveats:
* The library only in Python 3, so we need to keep on using imp for
  Python 2.
  * This requires Python version detection and using import statements
    locally.
* importlib.util is more fine-grained than expected, and requires:
  * Manually extracting module name from module path.
  * Explicitly adding loaded module to sys.modules. Meanwhile, once
    the module runs, the modules it transitively uses will be
    automatically added.

Fixed: 1069660
Change-Id: I41b6be8975db1219da006e0c9e5d98b42acf15c8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2145094
Reviewed-by: Andrew Grieve <agrieve@chromium.org>
Commit-Queue: Samuel Huang <huangs@chromium.org>
Cr-Original-Commit-Position: refs/heads/master@{#758136}
Cr-Mirrored-From: https://chromium.googlesource.com/chromium/src
Cr-Mirrored-Commit: 2c08fcf0aba8acce0c01515d75fe8b2baa939e35
This commit is contained in:
Samuel Huang 2020-04-10 05:28:18 +00:00 коммит произвёл Commit Bot
Родитель a312e0b403
Коммит 3c05fb4405
1 изменённых файлов: 17 добавлений и 3 удалений

Просмотреть файл

@ -12,7 +12,6 @@ This script should be compatible with Python 2 and Python 3.
"""
import argparse
import imp
import os
import pipes
import sys
@ -98,6 +97,22 @@ def _GetTargetPythonVersion(module):
return default_version
def _ImportModuleByPath(module_path):
"""Imports a module by its source file."""
sys.path[0] = os.path.dirname(module_path)
if sys.version_info[0] == 2:
import imp # Python 2 only, since it's deprecated in Python 3.
imp.load_source('NAME', module_path)
else:
# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
module_name = os.path.splitext(os.path.basename(module_path))[0]
import importlib.util # Python 3 only, since it's unavailable in Python 2.
spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
def main():
parser = argparse.ArgumentParser(
description='Prints all non-system dependencies for the given module.')
@ -155,8 +170,7 @@ def main():
# Replace the path entry for print_python_deps.py with the one for the given
# module.
try:
sys.path[0] = os.path.dirname(options.module)
imp.load_source('NAME', options.module)
_ImportModuleByPath(options.module)
except Exception:
# Output extra diagnostics when loading the script fails.
sys.stderr.write('Error running print_python_deps.py.\n')