1# Copyright 2023 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15# std_modules.py is a long-living program that communicates over STDIN and 16# STDOUT. STDIN receives module names, one per line. For each module statement 17# it evaluates, it outputs true/false for whether the module is part of the 18# standard library or not. 19 20import os 21import sys 22from contextlib import redirect_stdout 23 24 25def is_std_modules(module): 26 # If for some reason a module (such as pygame, see https://github.com/pygame/pygame/issues/542) 27 # prints to stdout upon import, 28 # the output of this script should still be parseable by golang. 29 # Therefore, redirect stdout while running the import. 30 with redirect_stdout(os.devnull): 31 try: 32 __import__(module, globals(), locals(), [], 0) 33 return True 34 except Exception: 35 return False 36 37 38def main(stdin, stdout): 39 for module in stdin: 40 module = module.strip() 41 # Don't print the boolean directly as it is capitalized in Python. 42 print( 43 "true" if is_std_modules(module) else "false", 44 end="\n", 45 file=stdout, 46 ) 47 stdout.flush() 48 49 50if __name__ == "__main__": 51 exit(main(sys.stdin, sys.stdout)) 52