__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env python3
  2. """Fortran to Python Interface Generator.
  3. """
  4. __all__ = ['run_main', 'compile', 'get_include']
  5. import sys
  6. import subprocess
  7. import os
  8. from . import f2py2e
  9. from . import diagnose
  10. run_main = f2py2e.run_main
  11. main = f2py2e.main
  12. def compile(source,
  13. modulename='untitled',
  14. extra_args='',
  15. verbose=True,
  16. source_fn=None,
  17. extension='.f',
  18. full_output=False
  19. ):
  20. """
  21. Build extension module from a Fortran 77 source string with f2py.
  22. Parameters
  23. ----------
  24. source : str or bytes
  25. Fortran source of module / subroutine to compile
  26. .. versionchanged:: 1.16.0
  27. Accept str as well as bytes
  28. modulename : str, optional
  29. The name of the compiled python module
  30. extra_args : str or list, optional
  31. Additional parameters passed to f2py
  32. .. versionchanged:: 1.16.0
  33. A list of args may also be provided.
  34. verbose : bool, optional
  35. Print f2py output to screen
  36. source_fn : str, optional
  37. Name of the file where the fortran source is written.
  38. The default is to use a temporary file with the extension
  39. provided by the ``extension`` parameter
  40. extension : ``{'.f', '.f90'}``, optional
  41. Filename extension if `source_fn` is not provided.
  42. The extension tells which fortran standard is used.
  43. The default is ``.f``, which implies F77 standard.
  44. .. versionadded:: 1.11.0
  45. full_output : bool, optional
  46. If True, return a `subprocess.CompletedProcess` containing
  47. the stdout and stderr of the compile process, instead of just
  48. the status code.
  49. .. versionadded:: 1.20.0
  50. Returns
  51. -------
  52. result : int or `subprocess.CompletedProcess`
  53. 0 on success, or a `subprocess.CompletedProcess` if
  54. ``full_output=True``
  55. Examples
  56. --------
  57. .. literalinclude:: ../../source/f2py/code/results/compile_session.dat
  58. :language: python
  59. """
  60. import tempfile
  61. import shlex
  62. if source_fn is None:
  63. f, fname = tempfile.mkstemp(suffix=extension)
  64. # f is a file descriptor so need to close it
  65. # carefully -- not with .close() directly
  66. os.close(f)
  67. else:
  68. fname = source_fn
  69. if not isinstance(source, str):
  70. source = str(source, 'utf-8')
  71. try:
  72. with open(fname, 'w') as f:
  73. f.write(source)
  74. args = ['-c', '-m', modulename, f.name]
  75. if isinstance(extra_args, str):
  76. is_posix = (os.name == 'posix')
  77. extra_args = shlex.split(extra_args, posix=is_posix)
  78. args.extend(extra_args)
  79. c = [sys.executable,
  80. '-c',
  81. 'import numpy.f2py as f2py2e;f2py2e.main()'] + args
  82. try:
  83. cp = subprocess.run(c, capture_output=True)
  84. except OSError:
  85. # preserve historic status code used by exec_command()
  86. cp = subprocess.CompletedProcess(c, 127, stdout=b'', stderr=b'')
  87. else:
  88. if verbose:
  89. print(cp.stdout.decode())
  90. finally:
  91. if source_fn is None:
  92. os.remove(fname)
  93. if full_output:
  94. return cp
  95. else:
  96. return cp.returncode
  97. def get_include():
  98. """
  99. Return the directory that contains the ``fortranobject.c`` and ``.h`` files.
  100. .. note::
  101. This function is not needed when building an extension with
  102. `numpy.distutils` directly from ``.f`` and/or ``.pyf`` files
  103. in one go.
  104. Python extension modules built with f2py-generated code need to use
  105. ``fortranobject.c`` as a source file, and include the ``fortranobject.h``
  106. header. This function can be used to obtain the directory containing
  107. both of these files.
  108. Returns
  109. -------
  110. include_path : str
  111. Absolute path to the directory containing ``fortranobject.c`` and
  112. ``fortranobject.h``.
  113. Notes
  114. -----
  115. .. versionadded:: 1.21.1
  116. Unless the build system you are using has specific support for f2py,
  117. building a Python extension using a ``.pyf`` signature file is a two-step
  118. process. For a module ``mymod``:
  119. * Step 1: run ``python -m numpy.f2py mymod.pyf --quiet``. This
  120. generates ``_mymodmodule.c`` and (if needed)
  121. ``_fblas-f2pywrappers.f`` files next to ``mymod.pyf``.
  122. * Step 2: build your Python extension module. This requires the
  123. following source files:
  124. * ``_mymodmodule.c``
  125. * ``_mymod-f2pywrappers.f`` (if it was generated in Step 1)
  126. * ``fortranobject.c``
  127. See Also
  128. --------
  129. numpy.get_include : function that returns the numpy include directory
  130. """
  131. return os.path.join(os.path.dirname(__file__), 'src')
  132. def __getattr__(attr):
  133. # Avoid importing things that aren't needed for building
  134. # which might import the main numpy module
  135. if attr == "test":
  136. from numpy._pytesttester import PytestTester
  137. test = PytestTester(__name__)
  138. return test
  139. else:
  140. raise AttributeError("module {!r} has no attribute "
  141. "{!r}".format(__name__, attr))
  142. def __dir__():
  143. return list(globals().keys() | {"test"})