blob: 5eedc180c8d8cfcab3661a6b8e3c1167918c51c1 [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
Cole Faustcaf766b2022-10-21 16:07:56 -070026 new_python_path = runfiles_path
Nan Zhangdb0b9a32017-02-27 10:12:13 -080027 old_python_path = os.environ.get(PYTHON_PATH)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080028
Nan Zhangdb0b9a32017-02-27 10:12:13 -080029 if old_python_path:
Cole Faustaf4b13d2022-09-14 15:25:15 -070030 os.environ.update({PYTHON_PATH: new_python_path + ":" + old_python_path})
31 else:
32 os.environ.update({PYTHON_PATH: new_python_path})
Nan Zhangdb0b9a32017-02-27 10:12:13 -080033
34 # Now look for main python source file.
35 main_filepath = os.path.join(runfiles_path, MAIN_FILE)
36 assert os.path.exists(main_filepath), \
37 'Cannot exec() %r: file not found.' % main_filepath
38 assert os.access(main_filepath, os.R_OK), \
39 'Cannot exec() %r: file not readable.' % main_filepath
40
Cole Faustaf4b13d2022-09-14 15:25:15 -070041 args = [PYTHON_BINARY, PYTHON_ARG, main_filepath] + args
Nan Zhangdb0b9a32017-02-27 10:12:13 -080042
43 sys.stdout.flush()
Cole Faustd02ca052022-09-09 10:27:15 -070044 # close_fds=False so that you can run binaries with files provided on the command line:
45 # my_python_app --file <(echo foo)
Cole Faustaf4b13d2022-09-14 15:25:15 -070046 sys.exit(subprocess.call(args, close_fds=False))
Nan Zhangdb0b9a32017-02-27 10:12:13 -080047 finally:
Cole Faustaf4b13d2022-09-14 15:25:15 -070048 shutil.rmtree(runfiles_path, ignore_errors=True)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080049
50if __name__ == '__main__':
51 Main()