utilities.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Kanged out of numpy.f2py.tests.util for test_build_ext
  2. from numpy.testing import IS_WASM
  3. import textwrap
  4. import shutil
  5. import tempfile
  6. import os
  7. import re
  8. import subprocess
  9. import sys
  10. #
  11. # Check if compilers are available at all...
  12. #
  13. _compiler_status = None
  14. def _get_compiler_status():
  15. global _compiler_status
  16. if _compiler_status is not None:
  17. return _compiler_status
  18. _compiler_status = (False, False, False)
  19. if IS_WASM:
  20. # Can't run compiler from inside WASM.
  21. return _compiler_status
  22. # XXX: this is really ugly. But I don't know how to invoke Distutils
  23. # in a safer way...
  24. code = textwrap.dedent(
  25. f"""\
  26. import os
  27. import sys
  28. sys.path = {repr(sys.path)}
  29. def configuration(parent_name='',top_path=None):
  30. global config
  31. from numpy.distutils.misc_util import Configuration
  32. config = Configuration('', parent_name, top_path)
  33. return config
  34. from numpy.distutils.core import setup
  35. setup(configuration=configuration)
  36. config_cmd = config.get_config_cmd()
  37. have_c = config_cmd.try_compile('void foo() {{}}')
  38. print('COMPILERS:%%d,%%d,%%d' %% (have_c,
  39. config.have_f77c(),
  40. config.have_f90c()))
  41. sys.exit(99)
  42. """
  43. )
  44. code = code % dict(syspath=repr(sys.path))
  45. tmpdir = tempfile.mkdtemp()
  46. try:
  47. script = os.path.join(tmpdir, "setup.py")
  48. with open(script, "w") as f:
  49. f.write(code)
  50. cmd = [sys.executable, "setup.py", "config"]
  51. p = subprocess.Popen(
  52. cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=tmpdir
  53. )
  54. out, err = p.communicate()
  55. finally:
  56. shutil.rmtree(tmpdir)
  57. m = re.search(rb"COMPILERS:(\d+),(\d+),(\d+)", out)
  58. if m:
  59. _compiler_status = (
  60. bool(int(m.group(1))),
  61. bool(int(m.group(2))),
  62. bool(int(m.group(3))),
  63. )
  64. # Finished
  65. return _compiler_status
  66. def has_c_compiler():
  67. return _get_compiler_status()[0]
  68. def has_f77_compiler():
  69. return _get_compiler_status()[1]
  70. def has_f90_compiler():
  71. return _get_compiler_status()[2]