blob: 2d1bd4a9badf72c259f1055a73a7ba3885b6e42f [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
Qiao Yang2a3a4262023-03-22 00:17:22 +00006import signal
Nan Zhangdb0b9a32017-02-27 10:12:13 -08007import sys
8import subprocess
9import zipfile
10
11PYTHON_BINARY = '%interpreter%'
12MAIN_FILE = '%main%'
13PYTHON_PATH = 'PYTHONPATH'
Nan Zhangdb0b9a32017-02-27 10:12:13 -080014
yangbill7265e5f2019-01-04 18:10:32 +080015# Don't imply 'import site' on initialization
16PYTHON_ARG = '-S'
17
Nan Zhangdb0b9a32017-02-27 10:12:13 -080018def Main():
19 args = sys.argv[1:]
20
Cole Faustaf4b13d2022-09-14 15:25:15 -070021 runfiles_path = tempfile.mkdtemp(prefix="Soong.python_")
Nan Zhangdb0b9a32017-02-27 10:12:13 -080022 try:
Cole Faustaf4b13d2022-09-14 15:25:15 -070023 zf = zipfile.ZipFile(os.path.dirname(__file__))
24 zf.extractall(runfiles_path)
25 zf.close()
Nan Zhangdb0b9a32017-02-27 10:12:13 -080026
Cole Faustcaf766b2022-10-21 16:07:56 -070027 new_python_path = runfiles_path
Nan Zhangdb0b9a32017-02-27 10:12:13 -080028 old_python_path = os.environ.get(PYTHON_PATH)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080029
Nan Zhangdb0b9a32017-02-27 10:12:13 -080030 if old_python_path:
Cole Faustaf4b13d2022-09-14 15:25:15 -070031 os.environ.update({PYTHON_PATH: new_python_path + ":" + old_python_path})
32 else:
33 os.environ.update({PYTHON_PATH: new_python_path})
Nan Zhangdb0b9a32017-02-27 10:12:13 -080034
35 # Now look for main python source file.
36 main_filepath = os.path.join(runfiles_path, MAIN_FILE)
37 assert os.path.exists(main_filepath), \
38 'Cannot exec() %r: file not found.' % main_filepath
39 assert os.access(main_filepath, os.R_OK), \
40 'Cannot exec() %r: file not readable.' % main_filepath
41
Cole Faustaf4b13d2022-09-14 15:25:15 -070042 args = [PYTHON_BINARY, PYTHON_ARG, main_filepath] + args
Nan Zhangdb0b9a32017-02-27 10:12:13 -080043
44 sys.stdout.flush()
Cole Faustd02ca052022-09-09 10:27:15 -070045 # close_fds=False so that you can run binaries with files provided on the command line:
46 # my_python_app --file <(echo foo)
Qiao Yang2a3a4262023-03-22 00:17:22 +000047 p = subprocess.Popen(args, close_fds=False)
48
49 def handler(sig, frame):
50 p.send_signal(sig)
51
52 # Redirect SIGINT and SIGTERM to subprocess
53 signal.signal(signal.SIGINT, handler)
54 signal.signal(signal.SIGTERM, handler)
55
56 p.wait()
57
58 sys.exit(p.returncode)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080059 finally:
Cole Faustaf4b13d2022-09-14 15:25:15 -070060 shutil.rmtree(runfiles_path, ignore_errors=True)
Nan Zhangdb0b9a32017-02-27 10:12:13 -080061
62if __name__ == '__main__':
63 Main()