blob: a0ddffe8243863d41643e68cd5a14a9ed8d8d095 [file] [log] [blame]
yangbill3aa29752021-04-16 16:00:28 +08001#!/usr/bin/env '%interpreter%'
Nan Zhangdb0b9a32017-02-27 10:12:13 -08002
3import os
Nan Zhangdb0b9a32017-02-27 10:12:13 -08004import tempfile
5import shutil
6import sys
7import subprocess
8import zipfile
9
10PYTHON_BINARY = '%interpreter%'
11MAIN_FILE = '%main%'
12PYTHON_PATH = 'PYTHONPATH'
Nan Zhangdb0b9a32017-02-27 10:12:13 -080013
yangbill7265e5f2019-01-04 18:10:32 +080014# Don't imply 'import site' on initialization
15PYTHON_ARG = '-S'
16
Nan Zhangdb0b9a32017-02-27 10:12:13 -080017def Main():
18 args = sys.argv[1:]
19
Cole Faustaf4b13d2022-09-14 15:25:15 -070020 runfiles_path = tempfile.mkdtemp(prefix="Soong.python_")
Nan Zhangdb0b9a32017-02-27 10:12:13 -080021 try:
Cole Faustaf4b13d2022-09-14 15:25:15 -070022 zf = zipfile.ZipFile(os.path.dirname(__file__))
23 zf.extractall(runfiles_path)
24 zf.close()
Nan Zhangdb0b9a32017-02-27 10:12:13 -080025
26 # Add runfiles path to PYTHONPATH.
27 python_path_entries = [runfiles_path]
28
Cole Faustaf4b13d2022-09-14 15:25:15 -070029 if ADD_TOP_DIRECTORIES_TO_PATH:
30 # Add top dirs within runfiles path to PYTHONPATH.
31 top_entries = [os.path.join(runfiles_path, i) for i in os.listdir(runfiles_path)]
32 top_pkg_dirs = [i for i in top_entries if os.path.isdir(i)]
33 python_path_entries += top_pkg_dirs
Nan Zhangdb0b9a32017-02-27 10:12:13 -080034
Cole Faustaf4b13d2022-09-14 15:25:15 -070035 new_python_path = ":".join(python_path_entries)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080036 old_python_path = os.environ.get(PYTHON_PATH)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080037
Nan Zhangdb0b9a32017-02-27 10:12:13 -080038 if old_python_path:
Cole Faustaf4b13d2022-09-14 15:25:15 -070039 os.environ.update({PYTHON_PATH: new_python_path + ":" + old_python_path})
40 else:
41 os.environ.update({PYTHON_PATH: new_python_path})
Nan Zhangdb0b9a32017-02-27 10:12:13 -080042
43 # Now look for main python source file.
44 main_filepath = os.path.join(runfiles_path, MAIN_FILE)
45 assert os.path.exists(main_filepath), \
46 'Cannot exec() %r: file not found.' % main_filepath
47 assert os.access(main_filepath, os.R_OK), \
48 'Cannot exec() %r: file not readable.' % main_filepath
49
Cole Faustaf4b13d2022-09-14 15:25:15 -070050 args = [PYTHON_BINARY, PYTHON_ARG, main_filepath] + args
Nan Zhangdb0b9a32017-02-27 10:12:13 -080051
52 sys.stdout.flush()
Cole Faustd02ca052022-09-09 10:27:15 -070053 # close_fds=False so that you can run binaries with files provided on the command line:
54 # my_python_app --file <(echo foo)
Cole Faustaf4b13d2022-09-14 15:25:15 -070055 sys.exit(subprocess.call(args, close_fds=False))
Nan Zhangdb0b9a32017-02-27 10:12:13 -080056 finally:
Cole Faustaf4b13d2022-09-14 15:25:15 -070057 shutil.rmtree(runfiles_path, ignore_errors=True)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080058
59if __name__ == '__main__':
60 Main()