def test_get_shared_lib_extension(self):
     import sys
     ext = get_shared_lib_extension(is_python_ext=False)
     if sys.platform.startswith('linux'):
         assert_equal(ext, '.so')
     elif sys.platform.startswith('gnukfreebsd'):
         assert_equal(ext, '.so')
     elif sys.platform.startswith('darwin'):
         assert_equal(ext, '.dylib')
     elif sys.platform.startswith('win'):
         assert_equal(ext, '.dll')
     # just check for no crash
     assert_(get_shared_lib_extension(is_python_ext=True))
Ejemplo n.º 2
0
 def test_get_shared_lib_extension(self):
     import sys
     ext = get_shared_lib_extension(is_python_ext=False)
     if sys.platform.startswith('linux'):
         assert_equal(ext, '.so')
     elif sys.platform.startswith('gnukfreebsd'):
         assert_equal(ext, '.so')
     elif sys.platform.startswith('darwin'):
         assert_equal(ext, '.dylib')
     elif sys.platform.startswith('win'):
         assert_equal(ext, '.dll')
     # just check for no crash
     assert_(get_shared_lib_extension(is_python_ext=True))
Ejemplo n.º 3
0
    def test_get_shared_lib_extension(self):
        import sys

        ext = get_shared_lib_extension(is_python_ext=False)
        if sys.platform.startswith("linux"):
            assert_equal(ext, ".so")
        elif sys.platform.startswith("gnukfreebsd"):
            assert_equal(ext, ".so")
        elif sys.platform.startswith("darwin"):
            assert_equal(ext, ".dylib")
        elif sys.platform.startswith("win"):
            assert_equal(ext, ".dll")
        # just check for no crash
        assert_(get_shared_lib_extension(is_python_ext=True))
Ejemplo n.º 4
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
            try:
                import sysconfig
                so_ext3 = '.%s-%s.so' % (sysconfig.get_config_var('SOABI'),
                                         sysconfig.get_config_var('MULTIARCH'))
                libname_ext.insert(0, libname + so_ext3)
            except (KeyError, ImportError):
                pass

        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 5
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
            try:
                import sysconfig
                so_ext3 = '.%s-%s.so' % (sysconfig.get_config_var('SOABI'),
                                         sysconfig.get_config_var('MULTIARCH'))
                libname_ext.insert(0, libname + so_ext3)
            except (KeyError, ImportError):
                pass

        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 6
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < "1.0.1":
            import warnings

            warnings.warn("All features of ctypes interface may not work " "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension

            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            if sys.version[:3] >= "3.2":
                # For Python >= 3.2 a tag may be added to lib extension
                # (platform dependent).  If we find such a tag, try both with
                # and without it.
                so_ext2 = get_shared_lib_extension(is_python_ext=True)
                if not so_ext2 == so_ext:
                    libname_ext.insert(0, libname + so_ext2)
            if sys.platform == "win32":
                libname_ext.insert(0, "%s.dll" % libname)
            elif sys.platform == "darwin":
                libname_ext.insert(0, "%s.dylib" % libname)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 7
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            if sys.version[:3] >= '3.2':
                # For Python >= 3.2 a tag may be added to lib extension
                # (platform dependent).  If we find such a tag, try both with
                # and without it.
                so_ext2 = get_shared_lib_extension(is_python_ext=True)
                if not so_ext2 == so_ext:
                    libname_ext.insert(0, libname + so_ext2)
            if sys.platform == 'win32':
                libname_ext.insert(0, '%s.dll' % libname)
            elif sys.platform == 'darwin':
                libname_ext.insert(0, '%s.dylib' % libname)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 8
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            if sys.version[:3] >= '3.2':
                # For Python >= 3.2 a tag may be added to lib extension
                # (platform dependent).  If we find such a tag, try both with
                # and without it.
                so_ext2 = get_shared_lib_extension(is_python_ext=True)
                if not so_ext2 == so_ext:
                    libname_ext.insert(0, libname + so_ext2)
            if sys.platform == 'win32':
                libname_ext.insert(0, '%s.dll' % libname)
            elif sys.platform == 'darwin':
                libname_ext.insert(0, '%s.dylib' % libname)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        # Need to save exception when using Python 3k, see PEP 3110.
        exc = None
        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError, exc:
                    ## defective lib file
                    raise exc
Ejemplo n.º 9
0
def load_library(libname: str) -> CDLL:
    """load library cross-platform compatible."""

    if not op.splitext(libname)[1]:
        # Try to load library with platform-specific name
        so_ext = get_shared_lib_extension()
        libname_ext = libname + so_ext
    else:
        libname_ext = libname

    return cdll.LoadLibrary(libname_ext)
Ejemplo n.º 10
0
 def test_basic2(self):
     # Regression for #801: load_library with a full library name
     # (including extension) does not work.
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             # Should succeed
             load_library("multiarray%s" % so, np.core.multiarray.__file__)
         except ImportError:
             print("No distutils available, skipping test.")
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" " (import error was: %s)" % str(e)
         print(msg)
Ejemplo n.º 11
0
 def test_basic2(self):
     """Regression for #801: load_library with a full library name
     (including extension) does not work."""
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             cdll = load_library('multiarray%s' % so,
                                 np.core.multiarray.__file__)
         except ImportError:
             print("No distutils available, skipping test.")
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" \
               " (import error was: %s)" % str(e)
         print(msg)
Ejemplo n.º 12
0
 def test_basic2(self):
     # Regression for #801: load_library with a full library name
     # (including extension) does not work.
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             # Should succeed
             load_library('_multiarray_umath%s' % so, np.core._multiarray_umath.__file__)
         except ImportError:
             print("No distutils available, skipping test.")
     except ImportError as e:
         msg = ("ctypes is not available on this python: skipping the test"
                " (import error was: %s)" % str(e))
         print(msg)
Ejemplo n.º 13
0
 def test_basic2(self):
     """Regression for #801: load_library with a full library name
     (including extension) does not work."""
     try:
         try:
             so = get_shared_lib_extension(is_python_ext=True)
             cdll = load_library('multiarray%s' % so,
                                 np.core.multiarray.__file__)
         except ImportError:
             print "No distutils available, skipping test."
     except ImportError as e:
         msg = "ctypes is not available on this python: skipping the test" \
               " (import error was: %s)" % str(e)
         print msg
Ejemplo n.º 14
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        # Need to save exception when using Python 3k, see PEP 3110.
        exc = None
        for ln in libname_ext:
            try:
                libpath = os.path.join(libdir, ln)
                return ctypes.cdll[libpath]
            except OSError as e:
                exc = e
        raise exc
Ejemplo n.º 15
0
    def load_library(libname, loader_path):
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1")

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        # Need to save exception when using Python 3k, see PEP 3110.
        exc = None
        for ln in libname_ext:
            try:
                libpath = os.path.join(libdir, ln)
                return ctypes.cdll[libpath]
            except OSError as e:
                exc = e
        raise exc
Ejemplo n.º 16
0
    def get_libomp_names(self):
        """Return list of OpenMP libraries to try, based on platform and
        compiler detected."""
        if cxx is None:
            # Can't tell what compiler we're using, guessing we need libgomp
            names = ['libgomp']
        else:
            cmd = [cxx, '--version']
            try:
                version_str = os.path.dirname(
                    check_output(cmd).decode().strip())
            except (OSError, CalledProcessError):
                version_str = ''

            if 'clang' in version_str:
                names = ['libomp', 'libiomp5', 'libgomp']
            elif version_str.startswith('Intel'):
                names = ['libiomp5']
            else:
                # Too many GCC flavors and version strings, make this the default
                # rather than try to detect if it's GCC
                names = ['libgomp']

        return [name + get_shared_lib_extension() for name in names]
Ejemplo n.º 17
0
    def load_library(libname, loader_path):
        """
        It is possible to load a library using

        >>> lib = ctypes.cdll[<full_path_name>] # doctest: +SKIP

        But there are cross-platform considerations, such as library file extensions,
        plus the fact Windows will just load the first library it finds with that name.
        NumPy supplies the load_library function as a convenience.

        .. versionchanged:: 1.20.0
            Allow libname and loader_path to take any
            :term:`python:path-like object`.

        Parameters
        ----------
        libname : path-like
            Name of the library, which can have 'lib' as a prefix,
            but without an extension.
        loader_path : path-like
            Where the library can be found.

        Returns
        -------
        ctypes.cdll[libpath] : library object
           A ctypes library object

        Raises
        ------
        OSError
            If there is no library with the expected extension, or the
            library is defective and cannot be loaded.
        """
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn(
                "All features of ctypes interface may not work "
                "with ctypes < 1.0.1",
                stacklevel=2)

        # Convert path-like objects into strings
        libname = os.fsdecode(libname)
        loader_path = os.fsdecode(loader_path)

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 18
0
    def load_library(libname, loader_path):
        """
        It is possible to load a library using 
        >>> lib = ctypes.cdll[<full_path_name>]

        But there are cross-platform considerations, such as library file extensions,
        plus the fact Windows will just load the first library it finds with that name.  
        NumPy supplies the load_library function as a convenience.

        Parameters
        ----------
        libname : str
            Name of the library, which can have 'lib' as a prefix,
            but without an extension.
        loader_path : str
            Where the library can be found.

        Returns
        -------
        ctypes.cdll[libpath] : library object
           A ctypes library object 

        Raises
        ------
        OSError
            If there is no library with the expected extension, or the 
            library is defective and cannot be loaded.
        """
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1", stacklevel=2)

        # iOS: the actual library path depends on the executable and APPDIR. We cannot create it in python
        # so we create it in callproc.c (py_dl_open).
        libpath = loader_path + '.' + libname
        return ctypes.cdll[libpath]
            
        # not iOS: 
        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
        else:
            libname_ext = [libname]

        import sys
        print("libname_ext = ", libname_ext, file = sys.__stderr__)
        
        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if True or os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 19
0
    def load_library(libname, loader_path):
        """
        It is possible to load a library using 
        >>> lib = ctypes.cdll[<full_path_name>]

        But there are cross-platform considerations, such as library file extensions,
        plus the fact Windows will just load the first library it finds with that name.  
        NumPy supplies the load_library function as a convenience.

        Parameters
        ----------
        libname : str
            Name of the library, which can have 'lib' as a prefix,
            but without an extension.
        loader_path : str
            Where the library can be found.

        Returns
        -------
        ctypes.cdll[libpath] : library object
           A ctypes library object 

        Raises
        ------
        OSError
            If there is no library with the expected extension, or the 
            library is defective and cannot be loaded.
        """
        if ctypes.__version__ < '1.0.1':
            import warnings
            warnings.warn("All features of ctypes interface may not work " \
                          "with ctypes < 1.0.1", stacklevel=2)

        ext = os.path.splitext(libname)[1]
        if not ext:
            # Try to load library with platform-specific name, otherwise
            # default to libname.[so|pyd].  Sometimes, these files are built
            # erroneously on non-linux platforms.
            from numpy.distutils.misc_util import get_shared_lib_extension
            so_ext = get_shared_lib_extension()
            libname_ext = [libname + so_ext]
            # mac, windows and linux >= py3.2 shared library and loadable
            # module have different extensions so try both
            so_ext2 = get_shared_lib_extension(is_python_ext=True)
            if not so_ext2 == so_ext:
                libname_ext.insert(0, libname + so_ext2)
        else:
            libname_ext = [libname]

        loader_path = os.path.abspath(loader_path)
        if not os.path.isdir(loader_path):
            libdir = os.path.dirname(loader_path)
        else:
            libdir = loader_path

        for ln in libname_ext:
            libpath = os.path.join(libdir, ln)
            if os.path.exists(libpath):
                try:
                    return ctypes.cdll[libpath]
                except OSError:
                    ## defective lib file
                    raise
        ## if no successful return in the libname_ext loop:
        raise OSError("no file with expected extension")
Ejemplo n.º 20
0
class FCompiler(CCompiler):
    """Abstract base class to define the interface that must be implemented
    by real Fortran compiler classes.

    Methods that subclasses may redefine:

        update_executables(), find_executables(), get_version()
        get_flags(), get_flags_opt(), get_flags_arch(), get_flags_debug()
        get_flags_f77(), get_flags_opt_f77(), get_flags_arch_f77(),
        get_flags_debug_f77(), get_flags_f90(), get_flags_opt_f90(),
        get_flags_arch_f90(), get_flags_debug_f90(),
        get_flags_fix(), get_flags_linker_so()

    DON'T call these methods (except get_version) after
    constructing a compiler instance or inside any other method.
    All methods, except update_executables() and find_executables(),
    may call the get_version() method.

    After constructing a compiler instance, always call customize(dist=None)
    method that finalizes compiler construction and makes the following
    attributes available:
      compiler_f77
      compiler_f90
      compiler_fix
      linker_so
      archiver
      ranlib
      libraries
      library_dirs
    """

    # These are the environment variables and distutils keys used.
    # Each configuration descripition is
    # (<hook name>, <environment variable>, <key in distutils.cfg>, <convert>)
    # The hook names are handled by the self._environment_hook method.
    #  - names starting with 'self.' call methods in this class
    #  - names starting with 'exe.' return the key in the executables dict
    #  - names like 'flags.YYY' return self.get_flag_YYY()
    # convert is either None or a function to convert a string to the
    # appropiate type used.

    distutils_vars = EnvironmentConfig(
        distutils_section='config_fc',
        noopt=(None, None, 'noopt', str2bool),
        noarch=(None, None, 'noarch', str2bool),
        debug=(None, None, 'debug', str2bool),
        verbose=(None, None, 'verbose', str2bool),
    )

    command_vars = EnvironmentConfig(
        distutils_section='config_fc',
        compiler_f77=('exe.compiler_f77', 'F77', 'f77exec', None),
        compiler_f90=('exe.compiler_f90', 'F90', 'f90exec', None),
        compiler_fix=('exe.compiler_fix', 'F90', 'f90exec', None),
        version_cmd=('exe.version_cmd', None, None, None),
        linker_so=('exe.linker_so', 'LDSHARED', 'ldshared', None),
        linker_exe=('exe.linker_exe', 'LD', 'ld', None),
        archiver=(None, 'AR', 'ar', None),
        ranlib=(None, 'RANLIB', 'ranlib', None),
    )

    flag_vars = EnvironmentConfig(
        distutils_section='config_fc',
        f77=('flags.f77', 'F77FLAGS', 'f77flags', flaglist),
        f90=('flags.f90', 'F90FLAGS', 'f90flags', flaglist),
        free=('flags.free', 'FREEFLAGS', 'freeflags', flaglist),
        fix=('flags.fix', None, None, flaglist),
        opt=('flags.opt', 'FOPT', 'opt', flaglist),
        opt_f77=('flags.opt_f77', None, None, flaglist),
        opt_f90=('flags.opt_f90', None, None, flaglist),
        arch=('flags.arch', 'FARCH', 'arch', flaglist),
        arch_f77=('flags.arch_f77', None, None, flaglist),
        arch_f90=('flags.arch_f90', None, None, flaglist),
        debug=('flags.debug', 'FDEBUG', 'fdebug', flaglist),
        debug_f77=('flags.debug_f77', None, None, flaglist),
        debug_f90=('flags.debug_f90', None, None, flaglist),
        flags=('self.get_flags', 'FFLAGS', 'fflags', flaglist),
        linker_so=('flags.linker_so', 'LDFLAGS', 'ldflags', flaglist),
        linker_exe=('flags.linker_exe', 'LDFLAGS', 'ldflags', flaglist),
        ar=('flags.ar', 'ARFLAGS', 'arflags', flaglist),
    )

    language_map = {
        '.f': 'f77',
        '.for': 'f77',
        '.F': 'f77',  # XXX: needs preprocessor
        '.ftn': 'f77',
        '.f77': 'f77',
        '.f90': 'f90',
        '.F90': 'f90',  # XXX: needs preprocessor
        '.f95': 'f90',
    }
    language_order = ['f90', 'f77']

    # These will be set by the subclass

    compiler_type = None
    compiler_aliases = ()
    version_pattern = None

    possible_executables = []
    executables = {
        'version_cmd': ["f77", "-v"],
        'compiler_f77': ["f77"],
        'compiler_f90': ["f90"],
        'compiler_fix': ["f90", "-fixed"],
        'linker_so': ["f90", "-shared"],
        'linker_exe': ["f90"],
        'archiver': ["ar", "-cr"],
        'ranlib': None,
    }

    # If compiler does not support compiling Fortran 90 then it can
    # suggest using another compiler. For example, gnu would suggest
    # gnu95 compiler type when there are F90 sources.
    suggested_f90_compiler = None

    compile_switch = "-c"
    object_switch = "-o "  # Ending space matters! It will be stripped
    # but if it is missing then object_switch
    # will be prefixed to object file name by
    # string concatenation.
    library_switch = "-o "  # Ditto!

    # Switch to specify where module files are created and searched
    # for USE statement.  Normally it is a string and also here ending
    # space matters. See above.
    module_dir_switch = None

    # Switch to specify where module files are searched for USE statement.
    module_include_switch = '-I'

    pic_flags = []  # Flags to create position-independent code

    src_extensions = [
        '.for', '.ftn', '.f77', '.f', '.f90', '.f95', '.F', '.F90'
    ]
    obj_extension = ".o"

    shared_lib_extension = get_shared_lib_extension()
    static_lib_extension = ".a"  # or .lib
    static_lib_format = "lib%s%s"  # or %s%s
    shared_lib_format = "%s%s"
    exe_extension = ""

    _exe_cache = {}

    _executable_keys = [
        'version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix',
        'linker_so', 'linker_exe', 'archiver', 'ranlib'
    ]

    # This will be set by new_fcompiler when called in
    # command/{build_ext.py, build_clib.py, config.py} files.
    c_compiler = None

    # extra_{f77,f90}_compile_args are set by build_ext.build_extension method
    extra_f77_compile_args = []
    extra_f90_compile_args = []

    def __init__(self, *args, **kw):
        CCompiler.__init__(self, *args, **kw)
        self.distutils_vars = self.distutils_vars.clone(self._environment_hook)
        self.command_vars = self.command_vars.clone(self._environment_hook)
        self.flag_vars = self.flag_vars.clone(self._environment_hook)
        self.executables = self.executables.copy()
        for e in self._executable_keys:
            if e not in self.executables:
                self.executables[e] = None

        # Some methods depend on .customize() being called first, so
        # this keeps track of whether that's happened yet.
        self._is_customised = False

    def __copy__(self):
        obj = self.__new__(self.__class__)
        obj.__dict__.update(self.__dict__)
        obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook)
        obj.command_vars = obj.command_vars.clone(obj._environment_hook)
        obj.flag_vars = obj.flag_vars.clone(obj._environment_hook)
        obj.executables = obj.executables.copy()
        return obj

    def copy(self):
        return self.__copy__()

    # Use properties for the attributes used by CCompiler. Setting them
    # as attributes from the self.executables dictionary is error-prone,
    # so we get them from there each time.
    def _command_property(key):
        def fget(self):
            assert self._is_customised
            return self.executables[key]

        return property(fget=fget)

    version_cmd = _command_property('version_cmd')
    compiler_f77 = _command_property('compiler_f77')
    compiler_f90 = _command_property('compiler_f90')
    compiler_fix = _command_property('compiler_fix')
    linker_so = _command_property('linker_so')
    linker_exe = _command_property('linker_exe')
    archiver = _command_property('archiver')
    ranlib = _command_property('ranlib')

    # Make our terminology consistent.
    def set_executable(self, key, value):
        self.set_command(key, value)

    def set_commands(self, **kw):
        for k, v in list(kw.items()):
            self.set_command(k, v)

    def set_command(self, key, value):
        if not key in self._executable_keys:
            raise ValueError("unknown executable '%s' for class %s" %
                             (key, self.__class__.__name__))
        if is_string(value):
            value = split_quoted(value)
        assert value is None or is_sequence_of_strings(value[1:]), (key, value)
        self.executables[key] = value

    ######################################################################
    ## Methods that subclasses may redefine. But don't call these methods!
    ## They are private to FCompiler class and may return unexpected
    ## results if used elsewhere. So, you have been warned..

    def find_executables(self):
        """Go through the self.executables dictionary, and attempt to
        find and assign appropiate executables.

        Executable names are looked for in the environment (environment
        variables, the distutils.cfg, and command line), the 0th-element of
        the command list, and the self.possible_executables list.

        Also, if the 0th element is "<F77>" or "<F90>", the Fortran 77
        or the Fortran 90 compiler executable is used, unless overridden
        by an environment setting.

        Subclasses should call this if overriden.
        """
        assert self._is_customised
        exe_cache = self._exe_cache

        def cached_find_executable(exe):
            if exe in exe_cache:
                return exe_cache[exe]
            fc_exe = find_executable(exe)
            exe_cache[exe] = exe_cache[fc_exe] = fc_exe
            return fc_exe

        def verify_command_form(name, value):
            if value is not None and not is_sequence_of_strings(value):
                raise ValueError("%s value %r is invalid in class %s" %
                                 (name, value, self.__class__.__name__))

        def set_exe(exe_key, f77=None, f90=None):
            cmd = self.executables.get(exe_key, None)
            if not cmd:
                return None
            # Note that we get cmd[0] here if the environment doesn't
            # have anything set
            exe_from_environ = getattr(self.command_vars, exe_key)
            if not exe_from_environ:
                possibles = [f90, f77] + self.possible_executables
            else:
                possibles = [exe_from_environ] + self.possible_executables

            seen = set()
            unique_possibles = []
            for e in possibles:
                if e == '<F77>':
                    e = f77
                elif e == '<F90>':
                    e = f90
                if not e or e in seen:
                    continue
                seen.add(e)
                unique_possibles.append(e)

            for exe in unique_possibles:
                fc_exe = cached_find_executable(exe)
                if fc_exe:
                    cmd[0] = fc_exe
                    return fc_exe
            self.set_command(exe_key, None)
            return None

        ctype = self.compiler_type
        f90 = set_exe('compiler_f90')
        if not f90:
            f77 = set_exe('compiler_f77')
            if f77:
                log.warn('%s: no Fortran 90 compiler found' % ctype)
            else:
                raise CompilerNotFound('%s: f90 nor f77' % ctype)
        else:
            f77 = set_exe('compiler_f77', f90=f90)
            if not f77:
                log.warn('%s: no Fortran 77 compiler found' % ctype)
            set_exe('compiler_fix', f90=f90)

        set_exe('linker_so', f77=f77, f90=f90)
        set_exe('linker_exe', f77=f77, f90=f90)
        set_exe('version_cmd', f77=f77, f90=f90)
        set_exe('archiver')
        set_exe('ranlib')

    def update_executables(elf):
        """Called at the beginning of customisation. Subclasses should
        override this if they need to set up the executables dictionary.

        Note that self.find_executables() is run afterwards, so the
        self.executables dictionary values can contain <F77> or <F90> as
        the command, which will be replaced by the found F77 or F90
        compiler.
        """
        pass

    def get_flags(self):
        """List of flags common to all compiler types."""
        return [] + self.pic_flags

    def _get_command_flags(self, key):
        cmd = self.executables.get(key, None)
        if cmd is None:
            return []
        return cmd[1:]

    def get_flags_f77(self):
        """List of Fortran 77 specific flags."""
        return self._get_command_flags('compiler_f77')

    def get_flags_f90(self):
        """List of Fortran 90 specific flags."""
        return self._get_command_flags('compiler_f90')

    def get_flags_free(self):
        """List of Fortran 90 free format specific flags."""
        return []

    def get_flags_fix(self):
        """List of Fortran 90 fixed format specific flags."""
        return self._get_command_flags('compiler_fix')

    def get_flags_linker_so(self):
        """List of linker flags to build a shared library."""
        return self._get_command_flags('linker_so')

    def get_flags_linker_exe(self):
        """List of linker flags to build an executable."""
        return self._get_command_flags('linker_exe')

    def get_flags_ar(self):
        """List of archiver flags. """
        return self._get_command_flags('archiver')

    def get_flags_opt(self):
        """List of architecture independent compiler flags."""
        return []

    def get_flags_arch(self):
        """List of architecture dependent compiler flags."""
        return []

    def get_flags_debug(self):
        """List of compiler flags to compile with debugging information."""
        return []

    get_flags_opt_f77 = get_flags_opt_f90 = get_flags_opt
    get_flags_arch_f77 = get_flags_arch_f90 = get_flags_arch
    get_flags_debug_f77 = get_flags_debug_f90 = get_flags_debug

    def get_libraries(self):
        """List of compiler libraries."""
        return self.libraries[:]

    def get_library_dirs(self):
        """List of compiler library directories."""
        return self.library_dirs[:]

    def get_version(self, force=False, ok_status=[0]):
        assert self._is_customised
        version = CCompiler.get_version(self, force=force, ok_status=ok_status)
        if version is None:
            raise CompilerNotFound()
        return version

    ############################################################

    ## Public methods:

    def customize(self, dist=None):
        """Customize Fortran compiler.

        This method gets Fortran compiler specific information from
        (i) class definition, (ii) environment, (iii) distutils config
        files, and (iv) command line (later overrides earlier).

        This method should be always called after constructing a
        compiler instance. But not in __init__ because Distribution
        instance is needed for (iii) and (iv).
        """
        log.info('customize %s' % (self.__class__.__name__))

        self._is_customised = True

        self.distutils_vars.use_distribution(dist)
        self.command_vars.use_distribution(dist)
        self.flag_vars.use_distribution(dist)

        self.update_executables()

        # find_executables takes care of setting the compiler commands,
        # version_cmd, linker_so, linker_exe, ar, and ranlib
        self.find_executables()

        noopt = self.distutils_vars.get('noopt', False)
        noarch = self.distutils_vars.get('noarch', noopt)
        debug = self.distutils_vars.get('debug', False)

        f77 = self.command_vars.compiler_f77
        f90 = self.command_vars.compiler_f90

        f77flags = []
        f90flags = []
        freeflags = []
        fixflags = []

        if f77:
            f77flags = self.flag_vars.f77
        if f90:
            f90flags = self.flag_vars.f90
            freeflags = self.flag_vars.free
        # XXX Assuming that free format is default for f90 compiler.
        fix = self.command_vars.compiler_fix
        if fix:
            fixflags = self.flag_vars.fix + f90flags

        oflags, aflags, dflags = [], [], []

        # examine get_flags_<tag>_<compiler> for extra flags
        # only add them if the method is different from get_flags_<tag>
        def get_flags(tag, flags):
            # note that self.flag_vars.<tag> calls self.get_flags_<tag>()
            flags.extend(getattr(self.flag_vars, tag))
            this_get = getattr(self, 'get_flags_' + tag)
            for name, c, flagvar in [('f77', f77, f77flags),
                                     ('f90', f90, f90flags),
                                     ('f90', fix, fixflags)]:
                t = '%s_%s' % (tag, name)
                if c and this_get is not getattr(self, 'get_flags_' + t):
                    flagvar.extend(getattr(self.flag_vars, t))

        if not noopt:
            get_flags('opt', oflags)
            if not noarch:
                get_flags('arch', aflags)
        if debug:
            get_flags('debug', dflags)

        fflags = self.flag_vars.flags + dflags + oflags + aflags

        if f77:
            self.set_commands(compiler_f77=[f77] + f77flags + fflags)
        if f90:
            self.set_commands(compiler_f90=[f90] + freeflags + f90flags +
                              fflags)
        if fix:
            self.set_commands(compiler_fix=[fix] + fixflags + fflags)

        #XXX: Do we need LDSHARED->SOSHARED, LDFLAGS->SOFLAGS
        linker_so = self.linker_so
        if linker_so:
            linker_so_flags = self.flag_vars.linker_so
            if sys.platform.startswith('aix'):
                python_lib = get_python_lib(standard_lib=1)
                ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
                python_exp = os.path.join(python_lib, 'config', 'python.exp')
                linker_so = [ld_so_aix] + linker_so + ['-bI:' + python_exp]
            self.set_commands(linker_so=linker_so + linker_so_flags)

        linker_exe = self.linker_exe
        if linker_exe:
            linker_exe_flags = self.flag_vars.linker_exe
            self.set_commands(linker_exe=linker_exe + linker_exe_flags)

        ar = self.command_vars.archiver
        if ar:
            arflags = self.flag_vars.ar
            self.set_commands(archiver=[ar] + arflags)

        self.set_library_dirs(self.get_library_dirs())
        self.set_libraries(self.get_libraries())

    def dump_properties(self):
        """Print out the attributes of a compiler instance."""
        props = []
        for key in list(self.executables.keys()) + \
                ['version','libraries','library_dirs',
                 'object_switch','compile_switch']:
            if hasattr(self, key):
                v = getattr(self, key)
                props.append((key, None, '= ' + repr(v)))
        props.sort()

        pretty_printer = FancyGetopt(props)
        for l in pretty_printer.generate_help("%s instance properties:" \
                                              % (self.__class__.__name__)):
            if l[:4] == '  --':
                l = '  ' + l[4:]
            print(l)

    ###################

    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
        """Compile 'src' to product 'obj'."""
        src_flags = {}
        if is_f_file(src) and not has_f90_header(src):
            flavor = ':f77'
            compiler = self.compiler_f77
            src_flags = get_f77flags(src)
            extra_compile_args = self.extra_f77_compile_args or []
        elif is_free_format(src):
            flavor = ':f90'
            compiler = self.compiler_f90
            if compiler is None:
                raise DistutilsExecError('f90 not supported by %s needed for %s'\
                      % (self.__class__.__name__,src))
            extra_compile_args = self.extra_f90_compile_args or []
        else:
            flavor = ':fix'
            compiler = self.compiler_fix
            if compiler is None:
                raise DistutilsExecError('f90 (fixed) not supported by %s needed for %s'\
                      % (self.__class__.__name__,src))
            extra_compile_args = self.extra_f90_compile_args or []
        if self.object_switch[-1] == ' ':
            o_args = [self.object_switch.strip(), obj]
        else:
            o_args = [self.object_switch.strip() + obj]

        assert self.compile_switch.strip()
        s_args = [self.compile_switch, src]

        if extra_compile_args:
            log.info('extra %s options: %r' \
                     % (flavor[1:], ' '.join(extra_compile_args)))

        extra_flags = src_flags.get(self.compiler_type, [])
        if extra_flags:
            log.info('using compile options from source: %r' \
                     % ' '.join(extra_flags))

        command = compiler + cc_args + extra_flags + s_args + o_args \
                  + extra_postargs + extra_compile_args

        display = '%s: %s' % (os.path.basename(compiler[0]) + flavor, src)
        try:
            self.spawn(command, display=display)
        except DistutilsExecError:
            msg = str(get_exception())
            raise CompileError(msg)

    def module_options(self, module_dirs, module_build_dir):
        options = []
        if self.module_dir_switch is not None:
            if self.module_dir_switch[-1] == ' ':
                options.extend(
                    [self.module_dir_switch.strip(), module_build_dir])
            else:
                options.append(self.module_dir_switch.strip() +
                               module_build_dir)
        else:
            print(('XXX: module_build_dir=%r option ignored' %
                   (module_build_dir)))
            print(('XXX: Fix module_dir_switch for ', self.__class__.__name__))
        if self.module_include_switch is not None:
            for d in [module_build_dir] + module_dirs:
                options.append('%s%s' % (self.module_include_switch, d))
        else:
            print(('XXX: module_dirs=%r option ignored' % (module_dirs)))
            print(('XXX: Fix module_include_switch for ',
                   self.__class__.__name__))
        return options

    def library_option(self, lib):
        return "-l" + lib

    def library_dir_option(self, dir):
        return "-L" + dir

    def link(self,
             target_desc,
             objects,
             output_filename,
             output_dir=None,
             libraries=None,
             library_dirs=None,
             runtime_library_dirs=None,
             export_symbols=None,
             debug=0,
             extra_preargs=None,
             extra_postargs=None,
             build_temp=None,
             target_lang=None):
        objects, output_dir = self._fix_object_args(objects, output_dir)
        libraries, library_dirs, runtime_library_dirs = \
            self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)

        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
                                   libraries)
        if is_string(output_dir):
            output_filename = os.path.join(output_dir, output_filename)
        elif output_dir is not None:
            raise TypeError("'output_dir' must be a string or None")

        if self._need_link(objects, output_filename):
            if self.library_switch[-1] == ' ':
                o_args = [self.library_switch.strip(), output_filename]
            else:
                o_args = [self.library_switch.strip() + output_filename]

            if is_string(self.objects):
                ld_args = objects + [self.objects]
            else:
                ld_args = objects + self.objects
            ld_args = ld_args + lib_opts + o_args
            if debug:
                ld_args[:0] = ['-g']
            if extra_preargs:
                ld_args[:0] = extra_preargs
            if extra_postargs:
                ld_args.extend(extra_postargs)
            self.mkpath(os.path.dirname(output_filename))
            if target_desc == CCompiler.EXECUTABLE:
                linker = self.linker_exe[:]
            else:
                linker = self.linker_so[:]
            command = linker + ld_args
            try:
                self.spawn(command)
            except DistutilsExecError:
                msg = str(get_exception())
                raise LinkError(msg)
        else:
            log.debug("skipping %s (up-to-date)", output_filename)

    def _environment_hook(self, name, hook_name):
        if hook_name is None:
            return None
        if is_string(hook_name):
            if hook_name.startswith('self.'):
                hook_name = hook_name[5:]
                hook = getattr(self, hook_name)
                return hook()
            elif hook_name.startswith('exe.'):
                hook_name = hook_name[4:]
                var = self.executables[hook_name]
                if var:
                    return var[0]
                else:
                    return None
            elif hook_name.startswith('flags.'):
                hook_name = hook_name[6:]
                hook = getattr(self, 'get_flags_' + hook_name)
                return hook()
        else:
            return hook_name()
Ejemplo n.º 21
0
def get_lib_extension():
    return misc_util.get_shared_lib_extension()
Ejemplo n.º 22
0
    def init_not_msvc(self):
        """ Find OpenMP library and try to load if using ctype interface. """
        # find_library() does not automatically search LD_LIBRARY_PATH
        # until Python 3.6+, so we explicitly add it.
        # LD_LIBRARY_PATH is used on Linux, while macOS uses DYLD_LIBRARY_PATH
        # and DYLD_FALLBACK_LIBRARY_PATH.
        env_vars = []
        if sys.platform == 'darwin':
            env_vars = ['DYLD_LIBRARY_PATH', 'DYLD_FALLBACK_LIBRARY_PATH']
        else:
            env_vars = ['LD_LIBRARY_PATH']

        paths = []
        for env_var in env_vars:
            env_paths = os.environ.get(env_var, '')
            if env_paths:
                paths.extend(env_paths.split(os.pathsep))

        libomp_names = self.get_libomp_names()

        if cxx is not None:
            for libomp_name in libomp_names:
                cmd = [
                    cxx, '-print-file-name=lib{}{}'.format(
                        libomp_name, get_shared_lib_extension())
                ]
                # The subprocess can fail in various ways, including because it
                # doesn't support '-print-file-name'. In that case just give up.
                try:
                    output = check_output(cmd, stderr=DEVNULL)
                    path = os.path.dirname(output.decode().strip())
                    if path:
                        paths.append(path)
                except (OSError, CalledProcessError):
                    pass

        for libomp_name in libomp_names:
            # Try to load find libomp shared library using loader search dirs
            libomp_path = find_library(libomp_name)

            # Try to use custom paths if lookup failed
            if not libomp_path:
                for path in paths:
                    candidate_path = os.path.join(
                        path, 'lib{}{}'.format(libomp_name,
                                               get_shared_lib_extension()))
                    if os.path.isfile(candidate_path):
                        libomp_path = candidate_path
                        break

            # Load the library
            if libomp_path:
                try:
                    self.libomp = ctypes.CDLL(libomp_path)
                except OSError:
                    raise ImportError(
                        "found openMP library '{}' but couldn't load it. "
                        "This may happen if you are cross-compiling.".format(
                            libomp_path))
                self.version = 45
                return

        raise ImportError(
            "I can't find a shared library for libomp, you may need to install it "
            "or adjust the {} environment variable.".format(env_vars[0]))
Ejemplo n.º 23
0
def get_lib_extension():
    return misc_util.get_shared_lib_extension()