Files
build_soong/python/scripts/stub_template_host.txt
Cole Faust af4b13dbe4 Add flag to not add top-level modules to PYTHONPATH
stub_template_host.txt added all the top-level modules to the
PYTHONPATH, which isn't correct, and caused absl.logging to
override the built-in logging module.

Removing this also makes it more consistent with python binaries
built with embedded_launcher: true. embedded_launcher: true
binaries don't add the top-level modules.

Fixes: 245583294
Test: m py_dont_add_top_level_dirs_test && out/host/linux-x86/testcases/py_dont_add_top_level_dirs_test/x86_64/py_dont_add_top_level_dirs_test
Change-Id: Id3069565d2b2c4b2bda0ff5301e757a7b4201751
2022-09-23 11:06:11 -07:00

61 lines
1.8 KiB
Plaintext

#!/usr/bin/env '%interpreter%'
import os
import tempfile
import shutil
import sys
import subprocess
import zipfile
PYTHON_BINARY = '%interpreter%'
MAIN_FILE = '%main%'
PYTHON_PATH = 'PYTHONPATH'
# Don't imply 'import site' on initialization
PYTHON_ARG = '-S'
def Main():
args = sys.argv[1:]
runfiles_path = tempfile.mkdtemp(prefix="Soong.python_")
try:
zf = zipfile.ZipFile(os.path.dirname(__file__))
zf.extractall(runfiles_path)
zf.close()
# Add runfiles path to PYTHONPATH.
python_path_entries = [runfiles_path]
if ADD_TOP_DIRECTORIES_TO_PATH:
# Add top dirs within runfiles path to PYTHONPATH.
top_entries = [os.path.join(runfiles_path, i) for i in os.listdir(runfiles_path)]
top_pkg_dirs = [i for i in top_entries if os.path.isdir(i)]
python_path_entries += top_pkg_dirs
new_python_path = ":".join(python_path_entries)
old_python_path = os.environ.get(PYTHON_PATH)
if old_python_path:
os.environ.update({PYTHON_PATH: new_python_path + ":" + old_python_path})
else:
os.environ.update({PYTHON_PATH: new_python_path})
# Now look for main python source file.
main_filepath = os.path.join(runfiles_path, MAIN_FILE)
assert os.path.exists(main_filepath), \
'Cannot exec() %r: file not found.' % main_filepath
assert os.access(main_filepath, os.R_OK), \
'Cannot exec() %r: file not readable.' % main_filepath
args = [PYTHON_BINARY, PYTHON_ARG, main_filepath] + args
sys.stdout.flush()
# close_fds=False so that you can run binaries with files provided on the command line:
# my_python_app --file <(echo foo)
sys.exit(subprocess.call(args, close_fds=False))
finally:
shutil.rmtree(runfiles_path, ignore_errors=True)
if __name__ == '__main__':
Main()