Ejemplo n.º 1
0
    def test_getsitepackages(self):
        site.PREFIXES = ['xoxo']
        dirs = site.getsitepackages()

        if (sys.platform == "darwin" and
            sysconfig.get_config_var("PYTHONFRAMEWORK")):
            # OS X framework builds
            site.PREFIXES = ['Python.framework']
            dirs = site.getsitepackages()
            self.assertEqual(len(dirs), 2)
            wanted = os.path.join('/Library',
                                  sysconfig.get_config_var("PYTHONFRAMEWORK"),
                                  '%d.%d' % sys.version_info[:2],
                                  'site-packages')
            self.assertEqual(dirs[1], wanted)
        elif os.sep == '/':
            # OS X non-framwework builds, Linux, FreeBSD, etc
            self.assertEqual(len(dirs), 1)
            wanted = os.path.join('xoxo', 'lib',
                                  'python%d.%d' % sys.version_info[:2],
                                  'site-packages')
            self.assertEqual(dirs[0], wanted)
        else:
            # other platforms
            self.assertEqual(len(dirs), 2)
            self.assertEqual(dirs[0], 'xoxo')
            wanted = os.path.join('xoxo', 'lib', 'site-packages')
            self.assertEqual(dirs[1], wanted)
Ejemplo n.º 2
0
def copy_python_lib(dest):
    files = []
    if sys.platform == 'win32':
        dllname = "python%s%s.dll" % sys.version_info[:2]
        # two location to try
        system32path = os.path.join("C:\\", "Windows", "System32")
        syswow64path = os.path.join("C:\\", "Windows", "SysWOW64")
        files.append(os.path.join(system32path, dllname))
        if "64" in platform.machine() and "64" in platform.architecture()[0]:
            files.append(os.path.join(syswow64path, dllname))
    elif sys.platform == 'linux':
        libname = sysconfig.get_config_var("INSTSONAME")
        libdir = sysconfig.get_config_var(
            'LIBDIR') + (sysconfig.get_config_var("multiarchsubdir") or "")
        files.append(os.path.join(libdir, libname))
    else:
        # osx
        pass

    dest_folder = os.path.abspath(dest)
    for path in files:
        if os.path.exists(path):
            fil = os.path.basename(path)
            root, ext = os.path.splitext(fil)
            to = os.path.join(dest_folder, fil)
            copy_file(path, to)
Ejemplo n.º 3
0
def main():
  """Command line utility to retrieve compilation options for python modules'
  """
  parser = argparse.ArgumentParser(
      description='Retrieves compilation options for python modules.')
  parser.add_argument('--libraries', help='Returns libraries',
                      action='store_true')
  parser.add_argument('--includes', help='Returns includes',
                      action='store_true')
  parser.add_argument('--library_dirs', help='Returns library_dirs',
                      action='store_true')
  opts = parser.parse_args()

  result = []

  if opts.libraries:
    python_lib = sysconfig.get_config_var('LDLIBRARY')
    if python_lib.endswith(".so"):
      python_lib = python_lib[:-3]
    if python_lib.startswith("lib"):
      python_lib = python_lib[3:]

    result.append(python_lib)

  if opts.includes:
    result.append(sysconfig.get_config_var('INCLUDEPY'))

  if opts.library_dirs:
    result.append(sysconfig.get_config_var('BINLIBDEST'))

  for x in result:
    print x
Ejemplo n.º 4
0
 def test_srcdir_independent_of_cwd(self):
     # srcdir should be independent of the current working directory
     # See Issues #15322, #15364.
     srcdir = sysconfig.get_config_var('srcdir')
     with change_cwd(os.pardir):
         srcdir2 = sysconfig.get_config_var('srcdir')
     self.assertEqual(srcdir, srcdir2)
Ejemplo n.º 5
0
def get_build_cflags():
  """Synthesize a CFLAGS env var from the current python env for building of C modules."""
  return '{} {} -I{}'.format(
    sysconfig.get_config_var('BASECFLAGS'),
    sysconfig.get_config_var('OPT'),
    sysconfig.get_path('include')
  )
Ejemplo n.º 6
0
def get_enable_shared():

    if WIN32:
        return True

    from sysconfig import get_config_var

    if LINUX:
        return get_config_var('Py_ENABLE_SHARED')

    if which('pkg-config') is None:
        exit(f'pkg-config is required and not found in path. Link to install: {LINK}')

    lib = '/Library/Frameworks/Mono.framework/Versions/Current/lib'

    # Create a symlink of framework lib/mono to python lib/mono
    dst = os.path.join(os.path.dirname(sys.executable)[:-3] + 'lib', 'mono')
    if os.path.exists(dst): os.remove(dst)
    os.symlink(os.path.join(lib, 'mono'), dst)

    paths = [path for path, dirs, files in os.walk(lib) if 'mono-2.pc' in files]
    os.environ['PKG_CONFIG_PATH'] = ':'.join(paths)

    if len(paths) == 0:
       exit(f'Could not find "mono-2.pc" in "{lib}" tree.')

    return get_config_var('Py_ENABLE_SHARED')
Ejemplo n.º 7
0
def fixup_build_ext(cmd):
    """Function needed to make build_ext tests pass.

    When Python was built with --enable-shared on Unix, -L. is not enough to
    find libpython<blah>.so, because regrtest runs in a tempdir, not in the
    source directory where the .so lives.

    When Python was built with in debug mode on Windows, build_ext commands
    need their debug attribute set, and it is not done automatically for
    some reason.

    This function handles both of these things.  Example use:

        cmd = build_ext(dist)
        support.fixup_build_ext(cmd)
        cmd.ensure_finalized()

    Unlike most other Unix platforms, Mac OS X embeds absolute paths
    to shared libraries into executables, so the fixup is not needed there.
    """
    if os.name == 'nt':
        cmd.debug = sys.executable.endswith('_d.exe')
    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
        # To further add to the shared builds fun on Unix, we can't just add
        # library_dirs to the Extension() instance because that doesn't get
        # plumbed through to the final compiler command.
        runshared = sysconfig.get_config_var('RUNSHARED')
        if runshared is None:
            cmd.library_dirs = ['.']
        else:
            if sys.platform == 'darwin':
                cmd.library_dirs = []
            else:
                name, equals, value = runshared.partition('=')
                cmd.library_dirs = value.split(os.pathsep)
Ejemplo n.º 8
0
def so_path(dir, filename):
    '''http://www.python.org/dev/peps/pep-3149/'''
    suffix = sysconfig.get_config_var('SO')
    if not suffix:
        soabi = sysconfig.get_config_var('SOABI')
        suffix = ".{}.so".format(soabi)
    return os.path.join(dir, filename + suffix)
Ejemplo n.º 9
0
def load_lib():
    """Find and load libspacepy

    Normally this will be in the directory where spacepy is installed,
    under libspacepy.

    @return: the open library
    @rtype: ctypes.CDLL or ctypes.WinDLL
    """
    libdir = os.path.dirname(os.path.abspath(__file__))
    if sys.platform == 'win32':
        libnames = ['spacepy.dll']
    elif sys.platform == 'darwin':
        libnames = ['libspacepy.dylib', 'libspacepy.so',
                  'spacepy.dylib', 'spacepy.so']
    else:
        libnames = ['libspacepy.so']
    if sysconfig:
        ext = sysconfig.get_config_var('EXT_SUFFIX')
        if ext is None:
            ext = sysconfig.get_config_var('SO')
        if ext:
            libnames.append('libspacepy' + ext)
            libnames.append('spacepy' + ext)

    libpath = None
    for n in libnames:
        libpath = os.path.join(libdir, n)
        if os.path.exists(libpath):
            break

    if libpath and os.path.exists(libpath):
        return ctypes.CDLL(libpath)
    else:
        return None
Ejemplo n.º 10
0
def test_cpython_abi_py2(debug, pymalloc, unicode_width, monkeypatch):
    has_soabi = sysconfig.get_config_var("SOABI")
    if platform.python_implementation() != "CPython" or has_soabi:
        diff_debug = debug != sysconfig.get_config_var("Py_DEBUG")
        diff_malloc = pymalloc != sysconfig.get_config_var("WITH_PYMALLOC")
        unicode_size = sysconfig.get_config_var("Py_UNICODE_SIZE")
        diff_unicode_size = unicode_size != unicode_width
        if diff_debug or diff_malloc or diff_unicode_size:
            config_vars = {
                "SOABI": None,
                "Py_DEBUG": int(debug),
                "WITH_PYMALLOC": int(pymalloc),
                "Py_UNICODE_SIZE": unicode_width,
            }
            monkeypatch.setattr(sysconfig, "get_config_var", config_vars.__getitem__)
    else:
        config_vars = {
            "SOABI": None,
            "Py_DEBUG": int(debug),
            "WITH_PYMALLOC": int(pymalloc),
            "Py_UNICODE_SIZE": unicode_width,
        }
        monkeypatch.setattr(sysconfig, "get_config_var", config_vars.__getitem__)
    options = ""
    if debug:
        options += "d"
    if pymalloc:
        options += "m"
    if unicode_width == 4:
        options += "u"
    assert "cp33{}".format(options) == tags._cpython_abi((3, 3))
Ejemplo n.º 11
0
 def _find_libpy3_windows(self, env):
     '''
     Find python3 libraries on Windows and also verify that the arch matches
     what we are building for.
     '''
     pyarch = sysconfig.get_platform()
     arch = detect_cpu_family(env.coredata.compilers)
     if arch == 'x86':
         arch = '32'
     elif arch == 'x86_64':
         arch = '64'
     else:
         # We can't cross-compile Python 3 dependencies on Windows yet
         mlog.log('Unknown architecture {!r} for'.format(arch),
                  mlog.bold(self.name))
         self.is_found = False
         return
     # Pyarch ends in '32' or '64'
     if arch != pyarch[-2:]:
         mlog.log('Need', mlog.bold(self.name),
                  'for {}-bit, but found {}-bit'.format(arch, pyarch[-2:]))
         self.is_found = False
         return
     inc = sysconfig.get_path('include')
     platinc = sysconfig.get_path('platinclude')
     self.compile_args = ['-I' + inc]
     if inc != platinc:
         self.compile_args.append('-I' + platinc)
     # Nothing exposes this directly that I coulf find
     basedir = sysconfig.get_config_var('base')
     vernum = sysconfig.get_config_var('py_version_nodot')
     self.link_args = ['-L{}/libs'.format(basedir),
                       '-lpython{}'.format(vernum)]
     self.version = sysconfig.get_config_var('py_version_short')
     self.is_found = True
Ejemplo n.º 12
0
def sysconfig2():
    # import sysconfig module - Provide access to Python’s configuration information
    import sysconfig

    # returns an installation path corresponding to the path name
    print("Path Name : ", sysconfig.get_path("stdlib"))
    print()

    # returns a string that identifies the current platform.
    print("Current Platform : ", sysconfig.get_platform())
    print()

    # returns the MAJOR.MINOR Python version number as a string
    print("Python Version Number : ", sysconfig.get_python_version())
    print()

    # returns a tuple containing all path names
    print("Path Names : ", sysconfig.get_path_names())
    print()

    # returns a tuple containing all schemes
    print("Scheme Names : ", sysconfig.get_scheme_names())
    print()

    # returns the value of a single variable name.
    print("Variable name LIBDIR : ", sysconfig.get_config_var('LIBDIR'))

    # returns the value of a single variable name.
    print("Variable name LIBDEST : ", sysconfig.get_config_var('LIBDEST'))
Ejemplo n.º 13
0
    def test_getsitepackages(self):
        site.PREFIXES = ["xoxo"]
        dirs = site.getsitepackages()

        if sys.platform in ("os2emx", "riscos"):
            self.assertEqual(len(dirs), 1)
            wanted = os.path.join("xoxo", "Lib", "site-packages")
            self.assertEqual(dirs[0], wanted)
        elif sys.platform == "darwin" and sysconfig.get_config_var("PYTHONFRAMEWORK"):
            # OS X framework builds
            site.PREFIXES = ["Python.framework"]
            dirs = site.getsitepackages()
            self.assertEqual(len(dirs), 3)
            wanted = os.path.join(
                "/Library", sysconfig.get_config_var("PYTHONFRAMEWORK"), sys.version[:3], "site-packages"
            )
            self.assertEqual(dirs[2], wanted)
        elif os.sep == "/":
            # OS X non-framwework builds, Linux, FreeBSD, etc
            self.assertEqual(len(dirs), 3)
            wanted = os.path.join("xoxo", "lib", "python" + sys.version[:3], "site-packages")
            self.assertEqual(dirs[0], wanted)
            wanted = os.path.join("xoxo", "lib", "site-python")
            self.assertEqual(dirs[1], wanted)
        else:
            # other platforms
            self.assertEqual(len(dirs), 2)
            self.assertEqual(dirs[0], "xoxo")
            wanted = os.path.join("xoxo", "lib", "site-packages")
            self.assertEqual(dirs[1], wanted)
Ejemplo n.º 14
0
def fixup_build_ext(cmd):
    """Function needed to make build_ext tests pass.
    
    When Python was build with --enable-shared on Unix, -L. is not good
    enough to find the libpython<blah>.so.  This is because regrtest runs
    it under a tempdir, not in the top level where the .so lives.  By the
    time we've gotten here, Python's already been chdir'd to the tempdir.
    
    When Python was built with in debug mode on Windows, build_ext commands
    need their debug attribute set, and it is not done automatically for
    some reason.
    
    This function handles both of these things.  Example use:
    
        cmd = build_ext(dist)
        support.fixup_build_ext(cmd)
        cmd.ensure_finalized()
    
    Unlike most other Unix platforms, Mac OS X embeds absolute paths
    to shared libraries into executables, so the fixup is not needed there.
    """
    if os.name == 'nt':
        cmd.debug = sys.executable.endswith('_d.exe')
    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
        runshared = sysconfig.get_config_var('RUNSHARED')
        if runshared is None:
            cmd.library_dirs = ['.']
        elif sys.platform == 'darwin':
            cmd.library_dirs = []
        else:
            name, equals, value = runshared.partition('=')
            cmd.library_dirs = [ d for d in value.split(os.pathsep) if d ]
    return
Ejemplo n.º 15
0
def copy_embeddable_python_dylib(dst):
    runtime = op.join(sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX'), sysconfig.get_config_var('LDLIBRARY'))
    filedest = op.join(dst, 'Python')
    shutil.copy(runtime, filedest)
    os.chmod(filedest, 0o774) # We need write permission to use install_name_tool
    cmd = 'install_name_tool -id @rpath/Python %s' % filedest
    print_and_do(cmd)
Ejemplo n.º 16
0
def fixup_build_ext(cmd):
    """Function needed to make build_ext tests pass.

    When Python was build with --enable-shared on Unix, -L. is not good
    enough to find the libpython<blah>.so.  This is because regrtest runs
    it under a tempdir, not in the top level where the .so lives.  By the
    time we've gotten here, Python's already been chdir'd to the tempdir.

    When Python was built with in debug mode on Windows, build_ext commands
    need their debug attribute set, and it is not done automatically for
    some reason.

    This function handles both of these things.  Example use:

        cmd = build_ext(dist)
        support.fixup_build_ext(cmd)
        cmd.ensure_finalized()
    """
    if os.name == 'nt':
        cmd.debug = sys.executable.endswith('_d.exe')
    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
        # To further add to the shared builds fun on Unix, we can't just add
        # library_dirs to the Extension() instance because that doesn't get
        # plumbed through to the final compiler command.
        runshared = sysconfig.get_config_var('RUNSHARED')
        if runshared is None:
            cmd.library_dirs = ['.']
        else:
            name, equals, value = runshared.partition('=')
            cmd.library_dirs = value.split(os.pathsep)
Ejemplo n.º 17
0
def candidate_names(suffix=SHLIB_SUFFIX):
    """
    Iterate over candidate file names of libpython.

    Yields
    ------
    name : str
        Candidate name libpython.
    """
    LDLIBRARY = sysconfig.get_config_var("LDLIBRARY")
    if LDLIBRARY:
        yield LDLIBRARY

    LIBRARY = sysconfig.get_config_var("LIBRARY")
    if LIBRARY:
        yield os.path.splitext(LIBRARY)[0] + suffix

    dlprefix = "" if is_windows else "lib"
    sysdata = dict(
        v=sys.version_info,
        # VERSION is X.Y in Linux/macOS and XY in Windows:
        VERSION=(sysconfig.get_config_var("VERSION") or
                 "{v.major}.{v.minor}".format(v=sys.version_info)),
        ABIFLAGS=(sysconfig.get_config_var("ABIFLAGS") or
                  sysconfig.get_config_var("abiflags") or ""),
    )

    for stem in [
            "python{VERSION}{ABIFLAGS}".format(**sysdata),
            "python{VERSION}".format(**sysdata),
            "python{v.major}".format(**sysdata),
            "python",
            ]:
        yield dlprefix + stem + suffix
Ejemplo n.º 18
0
def _find_python_dll_file(fail=False):
    logging.debug("Searching for Python shared library file")

    #
    # Prepare list of search directories
    #

    search_dirs = [sys.prefix]

    extra_search_dirs = [sysconfig.get_config_var(name) for name in PYTHON_LIB_DIR_CONFIG_VAR_NAMES]
    for extra_dir in extra_search_dirs:
        if extra_dir and not extra_dir in search_dirs and os.path.exists(extra_dir):
            search_dirs.append(extra_dir)

    if platform.system() == 'Windows':
        extra_search_dirs = _get_existing_subdirs(search_dirs, "DLLs")
        search_dirs = extra_search_dirs + search_dirs

    multi_arch_sub_dir = sysconfig.get_config_var('multiarchsubdir')
    if multi_arch_sub_dir:
        while multi_arch_sub_dir.startswith('/'):
            multi_arch_sub_dir = multi_arch_sub_dir[1:]
        extra_search_dirs = _get_existing_subdirs(search_dirs, multi_arch_sub_dir)
        search_dirs = extra_search_dirs + search_dirs

    logging.debug("Potential Python shared library search dirs: %s" % repr(search_dirs))

    #
    # Prepare list of possible library file names
    #

    vmaj = str(sys.version_info.major)
    vmin = str(sys.version_info.minor)

    if platform.system() == 'Windows':
        versions = (vmaj + vmin, vmaj, '')
        file_names = ['python' + v + '.dll' for v in versions]
    elif platform.system() == 'Darwin':
        versions = (vmaj + "." + vmin, vmaj, '')
        file_names = ['libpython' + v + '.dylib' for v in versions] + \
                     ['libpython' + v + '.so' for v in versions]
    else:
        versions = (vmaj + "." + vmin, vmaj, '')
        file_names = ['libpython' + v + '.so' for v in versions]

    logging.debug("Potential Python shared library file names: %s" % repr(file_names))

    python_dll_path = _find_file(search_dirs, *file_names)
    if python_dll_path:
        return python_dll_path

    python_dll_path = ctypes.util.find_library(PYTHON_LIB_NAME)
    if python_dll_path:
        logging.debug(
            "No Python shared library file found in all search paths. Using fallback %s" % repr(python_dll_path))
    elif fail:
        raise RuntimeError("can't find any Python shared library")

    return python_dll_path
Ejemplo n.º 19
0
def ocropus_find_file(fname, gz=True):
    """Search for `fname` in one of the OCRopus data directories, as well as
    the current directory). If `gz` is True, search also for gzipped files.

    Result of searching $fname is the first existing in:

        * $base/$fname
        * $base/$fname.gz       # if gz
        * $base/model/$fname
        * $base/model/$fname.gz # if gz
        * $base/data/$fname
        * $base/data/$fname.gz  # if gz
        * $base/gui/$fname
        * $base/gui/$fname.gz   # if gz

    $base can be four base paths:
        * `$OCROPUS_DATA` environment variable
        * current working directory
        * ../../../../share/ocropus from this file's install location
        * `/usr/local/share/ocropus`
        * `$PREFIX/share/ocropus` ($PREFIX being the Python installation 
           prefix, usually `/usr`)
    """
    possible_prefixes = []

    if os.getenv("OCROPUS_DATA"):
        possible_prefixes.append(os.getenv("OCROPUS_DATA"))

    possible_prefixes.append(os.curdir)

    possible_prefixes.append(os.path.normpath(os.path.join(
        os.path.dirname(inspect.getfile(inspect.currentframe())),
        os.pardir, os.pardir, os.pardir, os.pardir, "share", "ocropus")))

    possible_prefixes.append("/usr/local/share/ocropus")

    # datarootdir is None in windows so don't add it to search list
    if sysconfig.get_config_var("datarootdir") is not None:
        possible_prefixes.append(os.path.join(
            sysconfig.get_config_var("datarootdir"), "ocropus"))


    # Unique entries with preserved order in possible_prefixes
    # http://stackoverflow.com/a/15637398/201318
    possible_prefixes = [possible_prefixes[i] for i in
            sorted(numpy.unique(possible_prefixes, return_index=True)[1])]
    for prefix in possible_prefixes:
        if not os.path.isdir(prefix):
            continue
        for basename in [".", "models", "data", "gui"]:
            if not os.path.isdir(os.path.join(prefix, basename)):
                continue
            full = os.path.join(prefix, basename, fname)
            if os.path.exists(full):
                return full
            if gz and os.path.exists(full + ".gz"):
                return full + ".gz"

    raise FileNotFound(fname)
Ejemplo n.º 20
0
    def syspy_so_fpath(self, identifier):
        if self.use_multiarch_fnames:
            fname = '{}.{}-{}.so'.format(identifier, sysconfig.get_config_var('SOABI'),
                                         sysconfig.get_config_var('MULTIARCH'))
        else:
            fname = '{}.so'.format(identifier)

        return self.package_dpath().joinpath(fname)
Ejemplo n.º 21
0
def copy_embeddable_python_dylib(dst):
    if not sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX'):
        raise Exception("Python needs to be compiled with the -framework option. Aborting.")
    runtime = op.join(sysconfig.get_config_var('PYTHONFRAMEWORKPREFIX'), sysconfig.get_config_var('LDLIBRARY'))
    filedest = op.join(dst, 'Python')
    shutil.copy(runtime, filedest)
    os.chmod(filedest, 0o774) # We need write permission to use install_name_tool
    cmd = 'install_name_tool -id @rpath/Python %s' % filedest
    print_and_do(cmd)
Ejemplo n.º 22
0
def test_cpython_abi_py3(monkeypatch):
    has_soabi = bool(sysconfig.get_config_var("SOABI"))
    if platform.python_implementation() != "CPython" or not has_soabi:
        monkeypatch.setattr(
            sysconfig, "get_config_var", lambda key: "'cpython-37m-darwin'"
        )
    soabi = sysconfig.get_config_var("SOABI").split("-", 2)[1]
    result = tags._cpython_abi(sys.version_info[:2])
    assert result == "cp{soabi}".format(soabi=soabi)
Ejemplo n.º 23
0
 def test_user_similar(self):
     # Issue 8759 : make sure the posix scheme for the users
     # is similar to the global posix_prefix one
     base = get_config_var("base")
     user = get_config_var("userbase")
     for name in ("stdlib", "platstdlib", "purelib", "platlib"):
         global_path = get_path(name, "posix_prefix")
         user_path = get_path(name, "posix_user")
         self.assertEquals(user_path, global_path.replace(base, user))
Ejemplo n.º 24
0
def get_libraries(extralibs=[], debug=False):
    """Return the list of libraries to link against when building a
    shared extension.  On most platforms, this is just 'ext.libraries';
    on Windows, we add the Python library (eg. python20.dll).
    """
    # The python library is always needed on Windows.  For MSVC, this
    # is redundant, since the library is mentioned in a pragma in
    # pyconfig.h that MSVC groks.  The other Windows compilers all seem
    # to need it mentioned explicitly, though, so that's what we do.
    # Append '_d' to the python import library on debug builds.
    if sys.platform == "win32":
        template = "python%d%d"
        if debug:
            template = template + '_d'
        pythonlib = (template %
                     (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
        # don't extend ext.libraries, it may be shared with other
        # extensions, it is a reference to the original list
        return extralibs + [pythonlib]
    elif sys.platform[:6] == "cygwin":
        template = "python%d.%d"
        pythonlib = (template %
                     (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
        # don't extend ext.libraries, it may be shared with other
        # extensions, it is a reference to the original list
        return extralibs + [pythonlib]
    elif sys.platform[:6] == "atheos":
        from distutils import sysconfig

        template = "python%d.%d"
        pythonlib = (template %
                     (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
        # Get SHLIBS from Makefile
        extra = []
        for lib in sysconfig.get_config_var('SHLIBS').split():
            if lib.startswith('-l'):
                extra.append(lib[2:])
            else:
                extra.append(lib)
        # don't extend ext.libraries, it may be shared with other
        # extensions, it is a reference to the original list
        return extralibs + [pythonlib, "m"] + extra
    elif sys.platform == 'darwin':
        # Don't use the default code below
        return extralibs
    elif sys.platform[:3] == 'aix':
        # Don't use the default code below
        return extralibs
    else:
        from distutils import sysconfig
        if sysconfig.get_config_var('Py_ENABLE_SHARED'):
            pythonlib = 'python{}.{}{}'.format(
                sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff,
                sys.abiflags)
            return extralibs + [pythonlib]
        else:
            return extralibs
Ejemplo n.º 25
0
 def test_user_similar(self):
     # Issue 8759 : make sure the posix scheme for the users
     # is similar to the global posix_prefix one
     base = get_config_var('base')
     user = get_config_var('userbase')
     for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
         global_path = get_path(name, 'posix_prefix')
         user_path = get_path(name, 'posix_user')
         self.assertEqual(user_path, global_path.replace(base, user))
Ejemplo n.º 26
0
    def get_python_version():
        python_version = sysconfig.get_config_var('VERSION')

        if not python_version:
            python_version = sysconfig.get_config_var('py_version_short')

        if not python_version:
            python_version = ".".join(map(str, sys.version_info[:2]))

        return python_version
Ejemplo n.º 27
0
 def get_java2cpython_libdest(self):
     if is_win:
         python_lib_dir = os.path.join(
             sysconfig.get_config_var('platbase'),
             'LIBS')
         lib_name = "java2cpython" + SO
     else:
         python_lib_dir = sysconfig.get_config_var('LIBDIR')
         lib_name = "libjava2cpython" + SO
     return python_lib_dir, lib_name
Ejemplo n.º 28
0
    def __get_libres(self):
        '''
        Computes libpath based on whether module_name is set or not
        Returns-->list of str lib paths to try

        PEP3140: ABI version tagged .so files:
            https://www.python.org/dev/peps/pep-3149/

        There's still one unexplained bit: pypy adds '-' + sys._multiarch()
        at the end (looks like 'x86_64-linux-gnu'), but neither py2 or py3 do

        Additionally, in older releases of pypy (e.g. build f3ad1e1e1d62
        Aug-28-2015), sysconfig.get_config_var('SOABI') returns '' but
        shared library still has '.pypy-26' in the name!

        So for pypy we try this this variant anyway!

        _I_ think Py2 and Py3 _MAY_ start adding sys._multiarch at some time

        So, we generate three forms:
            1. With sys._multiarch
            2. Without sys._multiarch
            3. libpath as-is - always tried by self.__openlib anyway
        For different versions we try in different order (for efficiency):
            Python2                 Python3                 Pypy

            2 --> 1 --> 3           2 --> 1 --> 3           1 --> 2 --> 3
        '''
        if self._module_name is None:
            return []
        ending = '.so'
        base = self._libpath.rsplit(ending, 1)[0]
        abi = sysconfig.get_config_var('SOABI')
        if abi is not None:
            abi = '.' + abi
        else:
            abi = ''

        multi_arch = sysconfig.get_config_var('MULTIARCH')
        if multi_arch is None:
            multi_arch = ''
        else:
            multi_arch = '-' + multi_arch

        if PYPY:
            n1 = base + abi + multi_arch + ending
            n2 = base + abi + ending
        else:
            n1 = base + abi + ending
            n2 = base + abi + multi_arch + ending
        if PYPY:
            n3 = base + '.pypy-26' + ending
            return [n1, n2, n3]
        else:
            return [n1, n2]
Ejemplo n.º 29
0
 def test_srcdir_independent_of_cwd(self):
     # srcdir should be independent of the current working directory
     # See Issues #15322, #15364.
     srcdir = sysconfig.get_config_var('srcdir')
     cwd = os.getcwd()
     try:
         os.chdir('..')
         srcdir2 = sysconfig.get_config_var('srcdir')
     finally:
         os.chdir(cwd)
     self.assertEqual(srcdir, srcdir2)
Ejemplo n.º 30
0
def get_ext_suffix():
    """Determine library extension for various versions of Python."""
    ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
    if ext_suffix:
        return ext_suffix

    ext_suffix = sysconfig.get_config_var('SO')
    if ext_suffix:
        return ext_suffix

    return '.so'
Ejemplo n.º 31
0
# (c)2010 Dennis Kaarsemaker <[email protected]
# See COPYING for licensing details

import distutils.util
import glob
import os
import re
import signal
import sys
import subprocess
import unittest

so = '.so'
try:
    import sysconfig
    so = sysconfig.get_config_var('SO')
except ImportError:
    pass

curdir = os.path.dirname(__file__)
builddir = os.path.join(curdir, 'build', 'lib.%s-%s' % (distutils.util.get_platform(), sys.version[0:3]))

# Always run from the builddir
if not os.path.exists(builddir) or \
   not os.path.exists(os.path.join(builddir, 'prctl.py')) or \
   not os.path.exists(os.path.join(builddir, '_prctl' + so)) or \
   os.path.getmtime(os.path.join(curdir, 'prctl.py')) > os.path.getmtime(os.path.join(builddir, 'prctl.py')) or \
   os.path.getmtime(os.path.join(curdir, '_prctlmodule.c')) > os.path.getmtime(os.path.join(builddir, '_prctl' + so)):
     sys.stderr.write("Please build the extension first, using ./setup.py build\n")
     sys.exit(1)
sys.path.insert(0, builddir)
Ejemplo n.º 32
0
 def get_sysconfig__CONFIG_VARS(self):
     # make sure the dict is initialized
     sysconfig.get_config_var('prefix')
     return (id(sysconfig._CONFIG_VARS), sysconfig._CONFIG_VARS,
             dict(sysconfig._CONFIG_VARS))
Ejemplo n.º 33
0
                                      STDTESTS, NOTTESTS, PASSED, FAILED,
                                      ENV_CHANGED, SKIPPED, RESOURCE_DENIED,
                                      INTERRUPTED, CHILD_ERROR,
                                      PROGRESS_MIN_TIME, format_test_result)
from test.libregrtest.setup import setup_tests
from test import support
try:
    import gc
except ImportError:
    gc = None

# When tests are run from the Python build directory, it is best practice
# to keep the test files in a subfolder.  This eases the cleanup of leftover
# files using the "make distclean" command.
if sysconfig.is_python_build():
    TEMPDIR = sysconfig.get_config_var('abs_builddir')
    if TEMPDIR is None:
        # bpo-30284: On Windows, only srcdir is available. Using abs_builddir
        # mostly matters on UNIX when building Python out of the source tree,
        # especially when the source tree is read only.
        TEMPDIR = sysconfig.get_config_var('srcdir')
    TEMPDIR = os.path.join(TEMPDIR, 'build')
else:
    TEMPDIR = tempfile.gettempdir()
TEMPDIR = os.path.abspath(TEMPDIR)


def format_duration(seconds):
    if seconds < 1.0:
        return '%.0f ms' % (seconds * 1e3)
    if seconds < 60.0:
Ejemplo n.º 34
0
import threading
import unittest
import warnings
from test import support
from test.support import _4G, bigmemtest
from test.support.import_helper import import_fresh_module
from test.support import threading_helper
from http.client import HTTPException

# Were we compiled --with-pydebug or with #define Py_DEBUG?
COMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')

# default builtin hash module
default_builtin_hashes = {'md5', 'sha1', 'sha256', 'sha512', 'sha3', 'blake2'}
# --with-builtin-hashlib-hashes override
builtin_hashes = sysconfig.get_config_var("PY_BUILTIN_HASHLIB_HASHES")
if builtin_hashes is None:
    builtin_hashes = default_builtin_hashes
else:
    builtin_hashes = {
        m.strip() for m in builtin_hashes.strip('"').lower().split(",")
    }

# hashlib with and without OpenSSL backend for PBKDF2
# only import builtin_hashlib when all builtin hashes are available.
# Otherwise import prints noise on stderr
openssl_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
if builtin_hashes == default_builtin_hashes:
    builtin_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
else:
    builtin_hashlib = None
Ejemplo n.º 35
0
class TestSysConfig(unittest.TestCase):
    def setUp(self):
        super(TestSysConfig, self).setUp()
        self.sys_path = sys.path[:]
        # patching os.uname
        if hasattr(os, 'uname'):
            self.uname = os.uname
            self._uname = os.uname()
        else:
            self.uname = None
            self._set_uname(('', ) * 5)
        os.uname = self._get_uname
        # saving the environment
        self.name = os.name
        self.platform = sys.platform
        self.version = sys.version
        self.sep = os.sep
        self.join = os.path.join
        self.isabs = os.path.isabs
        self.splitdrive = os.path.splitdrive
        self._config_vars = sysconfig._CONFIG_VARS, copy(
            sysconfig._CONFIG_VARS)
        self._added_envvars = []
        self._changed_envvars = []
        for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'):
            if var in os.environ:
                self._changed_envvars.append((var, os.environ[var]))
            else:
                self._added_envvars.append(var)

    def tearDown(self):
        sys.path[:] = self.sys_path
        self._cleanup_testfn()
        if self.uname is not None:
            os.uname = self.uname
        else:
            del os.uname
        os.name = self.name
        sys.platform = self.platform
        sys.version = self.version
        os.sep = self.sep
        os.path.join = self.join
        os.path.isabs = self.isabs
        os.path.splitdrive = self.splitdrive
        sysconfig._CONFIG_VARS = self._config_vars[0]
        sysconfig._CONFIG_VARS.clear()
        sysconfig._CONFIG_VARS.update(self._config_vars[1])
        for var, value in self._changed_envvars:
            os.environ[var] = value
        for var in self._added_envvars:
            os.environ.pop(var, None)

        super(TestSysConfig, self).tearDown()

    def _set_uname(self, uname):
        self._uname = os.uname_result(uname)

    def _get_uname(self):
        return self._uname

    def _cleanup_testfn(self):
        path = TESTFN
        if os.path.isfile(path):
            os.remove(path)
        elif os.path.isdir(path):
            shutil.rmtree(path)

    def test_get_path_names(self):
        self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)

    def test_get_paths(self):
        scheme = get_paths()
        default_scheme = get_default_scheme()
        wanted = _expand_vars(default_scheme, None)
        wanted = sorted(wanted.items())
        scheme = sorted(scheme.items())
        self.assertEqual(scheme, wanted)

    def test_get_path(self):
        config_vars = get_config_vars()
        for scheme in _INSTALL_SCHEMES:
            for name in _INSTALL_SCHEMES[scheme]:
                expected = _INSTALL_SCHEMES[scheme][name].format(**config_vars)
                self.assertEqual(
                    os.path.normpath(get_path(name, scheme)),
                    os.path.normpath(expected),
                )

    def test_get_default_scheme(self):
        self.assertIn(get_default_scheme(), _INSTALL_SCHEMES)

    def test_get_preferred_schemes(self):
        expected_schemes = {'prefix', 'home', 'user'}

        # Windows.
        os.name = 'nt'
        schemes = _get_preferred_schemes()
        self.assertIsInstance(schemes, dict)
        self.assertEqual(set(schemes), expected_schemes)

        # Mac and Linux, shared library build.
        os.name = 'posix'
        schemes = _get_preferred_schemes()
        self.assertIsInstance(schemes, dict)
        self.assertEqual(set(schemes), expected_schemes)

        # Mac, framework build.
        os.name = 'posix'
        sys.platform = 'darwin'
        sys._framework = True
        self.assertIsInstance(schemes, dict)
        self.assertEqual(set(schemes), expected_schemes)

    def test_get_config_vars(self):
        cvars = get_config_vars()
        self.assertIsInstance(cvars, dict)
        self.assertTrue(cvars)

    def test_get_platform(self):
        # windows XP, 32bits
        os.name = 'nt'
        sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                       '[MSC v.1310 32 bit (Intel)]')
        sys.platform = 'win32'
        self.assertEqual(get_platform(), 'win32')

        # windows XP, amd64
        os.name = 'nt'
        sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                       '[MSC v.1310 32 bit (Amd64)]')
        sys.platform = 'win32'
        self.assertEqual(get_platform(), 'win-amd64')

        # macbook
        os.name = 'posix'
        sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
                       '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
        sys.platform = 'darwin'
        self._set_uname(('Darwin', 'macziade', '8.11.1',
                         ('Darwin Kernel Version 8.11.1: '
                          'Wed Oct 10 18:23:28 PDT 2007; '
                          'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'

        get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
                                       '-fwrapv -O3 -Wall -Wstrict-prototypes')

        maxint = sys.maxsize
        try:
            sys.maxsize = 2147483647
            self.assertEqual(get_platform(), 'macosx-10.3-ppc')
            sys.maxsize = 9223372036854775807
            self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
        finally:
            sys.maxsize = maxint

        self._set_uname(('Darwin', 'macziade', '8.11.1',
                         ('Darwin Kernel Version 8.11.1: '
                          'Wed Oct 10 18:23:28 PDT 2007; '
                          'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'

        get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
                                       '-fwrapv -O3 -Wall -Wstrict-prototypes')
        maxint = sys.maxsize
        try:
            sys.maxsize = 2147483647
            self.assertEqual(get_platform(), 'macosx-10.3-i386')
            sys.maxsize = 9223372036854775807
            self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
        finally:
            sys.maxsize = maxint

        # macbook with fat binaries (fat, universal or fat64)
        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
        get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
                                       '-fno-strict-aliasing -fno-common '
                                       '-dynamic -DNDEBUG -g -O3')

        self.assertEqual(get_platform(), 'macosx-10.4-fat')

        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
                                       '-fno-strict-aliasing -fno-common '
                                       '-dynamic -DNDEBUG -g -O3')

        self.assertEqual(get_platform(), 'macosx-10.4-intel')

        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['CFLAGS'] = (
            '-arch x86_64 -arch ppc -arch i386 -isysroot '
            '/Developer/SDKs/MacOSX10.4u.sdk  '
            '-fno-strict-aliasing -fno-common '
            '-dynamic -DNDEBUG -g -O3')
        self.assertEqual(get_platform(), 'macosx-10.4-fat3')

        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['CFLAGS'] = (
            '-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
            '/Developer/SDKs/MacOSX10.4u.sdk  '
            '-fno-strict-aliasing -fno-common '
            '-dynamic -DNDEBUG -g -O3')
        self.assertEqual(get_platform(), 'macosx-10.4-universal')

        _osx_support._remove_original_values(get_config_vars())
        get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
                                       '/Developer/SDKs/MacOSX10.4u.sdk  '
                                       '-fno-strict-aliasing -fno-common '
                                       '-dynamic -DNDEBUG -g -O3')

        self.assertEqual(get_platform(), 'macosx-10.4-fat64')

        for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
            _osx_support._remove_original_values(get_config_vars())
            get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
                                           '/Developer/SDKs/MacOSX10.4u.sdk  '
                                           '-fno-strict-aliasing -fno-common '
                                           '-dynamic -DNDEBUG -g -O3' % arch)

            self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch)

        # linux debian sarge
        os.name = 'posix'
        sys.version = ('2.3.5 (#1, Jul  4 2007, 17:28:59) '
                       '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
        sys.platform = 'linux2'
        self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
                         '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))

        self.assertEqual(get_platform(), 'linux-i686')

        # XXX more platforms to tests here

    def test_get_config_h_filename(self):
        config_h = sysconfig.get_config_h_filename()
        self.assertTrue(os.path.isfile(config_h), config_h)

    def test_get_scheme_names(self):
        wanted = ['nt', 'posix_home', 'posix_prefix', 'rpm_prefix', 'venv']
        if HAS_USER_BASE:
            wanted.extend(['nt_user', 'osx_framework_user', 'posix_user'])
        self.assertEqual(get_scheme_names(), tuple(sorted(wanted)))

    @skip_unless_symlink
    def test_symlink(self):  # Issue 7880
        with PythonSymlink() as py:
            cmd = "-c", "import sysconfig; print(sysconfig.get_platform())"
            self.assertEqual(py.call_real(*cmd), py.call_link(*cmd))

    @unittest.skipIf('RPM_BUILD_ROOT' not in os.environ,
                     "Test doesn't expect Fedora's paths")
    def test_user_similar(self):
        # Issue #8759: make sure the posix scheme for the users
        # is similar to the global posix_prefix one
        base = get_config_var('base')
        if HAS_USER_BASE:
            user = get_config_var('userbase')
        # the global scheme mirrors the distinction between prefix and
        # exec-prefix but not the user scheme, so we have to adapt the paths
        # before comparing (issue #9100)
        adapt = sys.base_prefix != sys.base_exec_prefix
        for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
            global_path = get_path(name, 'posix_prefix')
            if adapt:
                global_path = global_path.replace(sys.exec_prefix,
                                                  sys.base_prefix)
                base = base.replace(sys.exec_prefix, sys.base_prefix)
            elif sys.base_prefix != sys.prefix:
                # virtual environment? Likewise, we have to adapt the paths
                # before comparing
                global_path = global_path.replace(sys.base_prefix, sys.prefix)
                base = base.replace(sys.base_prefix, sys.prefix)
            if HAS_USER_BASE:
                user_path = get_path(name, 'posix_user')
                expected = global_path.replace(base, user, 1)
                # bpo-44860: platlib of posix_user doesn't use sys.platlibdir,
                # whereas posix_prefix does.
                if name == 'platlib':
                    # Replace "/lib64/python3.11/site-packages" suffix
                    # with "/lib/python3.11/site-packages".
                    py_version_short = sysconfig.get_python_version()
                    suffix = f'python{py_version_short}/site-packages'
                    expected = expected.replace(f'/{sys.platlibdir}/{suffix}',
                                                f'/lib/{suffix}')
                self.assertEqual(user_path, expected)

    def test_main(self):
        # just making sure _main() runs and returns things in the stdout
        with captured_stdout() as output:
            _main()
        self.assertTrue(len(output.getvalue().split('\n')) > 0)

    @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
    def test_ldshared_value(self):
        ldflags = sysconfig.get_config_var('LDFLAGS')
        ldshared = sysconfig.get_config_var('LDSHARED')

        self.assertIn(ldflags, ldshared)

    @unittest.skipUnless(sys.platform == "darwin",
                         "test only relevant on MacOSX")
    def test_platform_in_subprocess(self):
        my_platform = sysconfig.get_platform()

        # Test without MACOSX_DEPLOYMENT_TARGET in the environment

        env = os.environ.copy()
        if 'MACOSX_DEPLOYMENT_TARGET' in env:
            del env['MACOSX_DEPLOYMENT_TARGET']

        p = subprocess.Popen([
            sys.executable,
            '-c',
            'import sysconfig; print(sysconfig.get_platform())',
        ],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.DEVNULL,
                             env=env)
        test_platform = p.communicate()[0].strip()
        test_platform = test_platform.decode('utf-8')
        status = p.wait()

        self.assertEqual(status, 0)
        self.assertEqual(my_platform, test_platform)

        # Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
        # using a value that is unlikely to be the default one.
        env = os.environ.copy()
        env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'

        p = subprocess.Popen([
            sys.executable,
            '-c',
            'import sysconfig; print(sysconfig.get_platform())',
        ],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.DEVNULL,
                             env=env)
        test_platform = p.communicate()[0].strip()
        test_platform = test_platform.decode('utf-8')
        status = p.wait()

        self.assertEqual(status, 0)
        self.assertEqual(my_platform, test_platform)

    def test_srcdir(self):
        # See Issues #15322, #15364.
        srcdir = sysconfig.get_config_var('srcdir')

        self.assertTrue(os.path.isabs(srcdir), srcdir)
        self.assertTrue(os.path.isdir(srcdir), srcdir)

        if sysconfig._PYTHON_BUILD:
            # The python executable has not been installed so srcdir
            # should be a full source checkout.
            Python_h = os.path.join(srcdir, 'Include', 'Python.h')
            self.assertTrue(os.path.exists(Python_h), Python_h)
            self.assertTrue(sysconfig._is_python_source_dir(srcdir))
        elif os.name == 'posix':
            makefile_dir = os.path.dirname(sysconfig.get_makefile_filename())
            # Issue #19340: srcdir has been realpath'ed already
            makefile_dir = os.path.realpath(makefile_dir)
            self.assertEqual(makefile_dir, srcdir)

    def test_srcdir_independent_of_cwd(self):
        # srcdir should be independent of the current working directory
        # See Issues #15322, #15364.
        srcdir = sysconfig.get_config_var('srcdir')
        with change_cwd(os.pardir):
            srcdir2 = sysconfig.get_config_var('srcdir')
        self.assertEqual(srcdir, srcdir2)

    @unittest.skipIf(
        sysconfig.get_config_var('EXT_SUFFIX') is None,
        'EXT_SUFFIX required for this test')
    def test_SO_deprecation(self):
        self.assertWarns(DeprecationWarning, sysconfig.get_config_var, 'SO')

    @unittest.skipIf(
        sysconfig.get_config_var('EXT_SUFFIX') is None,
        'EXT_SUFFIX required for this test')
    def test_SO_value(self):
        with check_warnings(('', DeprecationWarning)):
            self.assertEqual(sysconfig.get_config_var('SO'),
                             sysconfig.get_config_var('EXT_SUFFIX'))

    @unittest.skipIf(
        sysconfig.get_config_var('EXT_SUFFIX') is None,
        'EXT_SUFFIX required for this test')
    def test_EXT_SUFFIX_in_vars(self):
        import _imp
        vars = sysconfig.get_config_vars()
        self.assertIsNotNone(vars['SO'])
        self.assertEqual(vars['SO'], vars['EXT_SUFFIX'])
        self.assertEqual(vars['EXT_SUFFIX'], _imp.extension_suffixes()[0])

    @unittest.skipUnless(sys.platform == 'linux'
                         and hasattr(sys.implementation, '_multiarch'),
                         'multiarch-specific test')
    def test_triplet_in_ext_suffix(self):
        ctypes = import_module('ctypes')
        import platform, re
        machine = platform.machine()
        suffix = sysconfig.get_config_var('EXT_SUFFIX')
        if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine):
            self.assertTrue('linux' in suffix, suffix)
        if re.match('(i[3-6]86|x86_64)$', machine):
            if ctypes.sizeof(ctypes.c_char_p()) == 4:
                self.assertTrue(
                    suffix.endswith('i386-linux-gnu.so')
                    or suffix.endswith('x86_64-linux-gnux32.so'), suffix)
            else:  # 8 byte pointer size
                self.assertTrue(suffix.endswith('x86_64-linux-gnu.so'), suffix)

    @unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test')
    def test_osx_ext_suffix(self):
        suffix = sysconfig.get_config_var('EXT_SUFFIX')
        self.assertTrue(suffix.endswith('-darwin.so'), suffix)
Ejemplo n.º 36
0
def _build_dependency(name, patches=[]):
    import shutil
    from rpython.tool.runsubprocess import run_subprocess

    try:
        from urllib.request import urlretrieve
    except ImportError:
        from urllib import urlretrieve

    try:
        url, dgst, build_cmds = cffi_dependencies[name]
    except KeyError:
        return 0, None, None

    archive_dir = os.path.join(tempfile.gettempdir(), 'pypy-archives')

    if not os.path.isdir(archive_dir):
        os.makedirs(archive_dir)

    archive = os.path.join(archive_dir, url.rsplit('/', 1)[-1])

    # next, fetch the archive to disk, if needed
    if not os.path.exists(archive) or _sha256(archive) != dgst:
        print('fetching archive', url, file=sys.stderr)
        urlretrieve(url, archive)

    # make sure the hash matches
    if _sha256(archive) != dgst:
        return 1, '{} archive {} hash mismatch'.format(name, archive), ''

    shutil.rmtree(deps_destdir, ignore_errors=True)
    os.makedirs(deps_destdir)

    # extract the into our destination directory
    print('unpacking archive', archive, file=sys.stderr)
    _unpack_tarfile(archive, deps_destdir)

    sources = os.path.join(
        deps_destdir,
        os.path.basename(archive).rsplit('.', 2)[0],
    )

    # apply any patches
    if patches:
        for patch in patches:
            print('applying patch', patch, file=sys.stderr)
            status, stdout, stderr = run_subprocess(
                '/usr/bin/patch',
                ['-p1', '-i', patch],
                cwd=sources,
            )

            if status != 0:
                return status, stdout, stderr
    env = os.environ
    if sys.platform == 'darwin':
        target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
        if target:
            # override the value for building support libraries
            env = os.environ.copy()
            env['MACOSX_DEPLOYMENT_TARGET'] = target
            print('setting MACOSX_DEPLOYMENT_TARGET to "{}"'.format(target))

    for args in build_cmds:
        print('running', ' '.join(args), 'in', sources, file=sys.stderr)
        status, stdout, stderr = run_subprocess(args[0],
                                                args[1:],
                                                cwd=sources,
                                                env=env)
        if status != 0:
            break
    return status, stdout, stderr
Ejemplo n.º 37
0
 def test_sysconfig_module(self):
     import sysconfig as global_sysconfig
     self.assertEqual(global_sysconfig.get_config_var('CFLAGS'),
                      sysconfig.get_config_var('CFLAGS'))
     self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'),
                      sysconfig.get_config_var('LDFLAGS'))
Ejemplo n.º 38
0
        # Debug hooks must raise an error if PyMem_Malloc() is called
        # without holding the GIL
        code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
        self.check_malloc_without_gil(code)

    def test_pyobject_malloc_without_gil(self):
        # Debug hooks must raise an error if PyObject_Malloc() is called
        # without holding the GIL
        code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
        self.check_malloc_without_gil(code)


class PyMemMallocDebugTests(PyMemDebugTests):
    PYTHONMALLOC = 'malloc_debug'


@unittest.skipUnless(
    sysconfig.get_config_var('WITH_PYMALLOC') == 1, 'need pymalloc')
class PyMemPymallocDebugTests(PyMemDebugTests):
    PYTHONMALLOC = 'pymalloc_debug'


@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
class PyMemDefaultTests(PyMemDebugTests):
    # test default allocator of Python compiled in debug mode
    PYTHONMALLOC = ''


if __name__ == "__main__":
    unittest.main()
Ejemplo n.º 39
0
def main():

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    # These are neede for source fetching
    cmake_source_dir = "opencv"
    build_contrib = get_build_env_var_by_name("contrib")
    # headless flag to skip GUI deps if needed
    build_headless = get_build_env_var_by_name("headless")

    # Only import 3rd-party modules after having installed all the build dependencies:
    # any of them, or their dependencies, can be updated during that process,
    # leading to version conflicts
    minimum_supported_numpy = "1.11.1"

    if sys.version_info[:2] >= (3, 6):
        minimum_supported_numpy = "1.11.3"
    if sys.version_info[:2] >= (3, 7):
        minimum_supported_numpy = "1.14.5"

    numpy_version = get_or_install("numpy", minimum_supported_numpy)
    get_or_install("scikit-build")
    import skbuild

    if os.path.exists('.git'):

        import pip._internal.vcs.git as git
        g = git.Git(
        )  # NOTE: pip API's are internal, this has to be refactored

        g.run_command(["submodule", "sync"])
        g.run_command(
            ["submodule", "update", "--init", "--recursive", cmake_source_dir])

        # if build_contrib:
        g.run_command(
            ["submodule", "update", "--init", "--recursive", "opencv_contrib"])

    # https://stackoverflow.com/questions/1405913/python-32bit-or-64bit-mode
    x64 = sys.maxsize > 2**32

    package_name = "opencv-contrib-python"

    print("installing " + package_name)

    # if build_contrib and not build_headless:
    # package_name = "opencv-contrib-python"

    # if build_contrib and build_headless:
    # package_name = "opencv-contrib-python-headless"

    # if build_headless and not build_contrib:
    # package_name = "opencv-python-headless"

    long_description = io.open('README.md', encoding="utf-8").read()
    package_version = get_opencv_version()

    packages = ['cv2', 'cv2.data']

    package_data = {
        'cv2': ['*%s' % sysconfig.get_config_var('SO')] +
        (['*.dll'] if os.name == 'nt' else []) +
        ["LICENSE.txt", "LICENSE-3RD-PARTY.txt"],
        'cv2.data': ["*.xml"]
    }

    # Files from CMake output to copy to package.
    # Path regexes with forward slashes relative to CMake install dir.
    rearrange_cmake_output_data = {
        'cv2': ([r'bin/opencv_ffmpeg\d{3}%s\.dll' %
                 ('_64' if x64 else '')] if os.name == 'nt' else []) +
        # In Windows, in python/X.Y/<arch>/; in Linux, in just python/X.Y/.
        # Naming conventions vary so widely between versions and OSes
        # had to give up on checking them.
        [
            'python/cv2[^/]*%(ext)s' % {
                'ext': re.escape(sysconfig.get_config_var('SO'))
            }
        ],
        'cv2.data': [  # OPENCV_OTHER_INSTALL_PATH
            ('etc' if os.name == 'nt' else 'share/opencv4') +
            r'/haarcascades/.*\.xml'
        ]
    }

    # Files in sourcetree outside package dir that should be copied to package.
    # Raw paths relative to sourcetree root.
    files_outside_package_dir = {
        'cv2': ['LICENSE.txt', 'LICENSE-3RD-PARTY.txt']
    }

    cmake_args = ([
        "-G", "Visual Studio 14" + (" Win64" if x64 else '')
    ] if os.name == 'nt' else [
        "-G",
        "Unix Makefiles"  # don't make CMake try (and fail) Ninja first
    ]) + [
        # skbuild inserts PYTHON_* vars. That doesn't satisfy opencv build scripts in case of Py3
        "-DPYTHON%d_EXECUTABLE=%s" % (sys.version_info[0], sys.executable),
        "-DBUILD_opencv_python%d=ON" % sys.version_info[0],
        "-DOPENCV_SKIP_PYTHON_LOADER=ON",
        "-DOPENCV_PYTHON2_INSTALL_PATH=python",
        "-DOPENCV_PYTHON3_INSTALL_PATH=python",
        # Otherwise, opencv scripts would want to install `.pyd' right into site-packages,
        # and skbuild bails out on seeing that
        "-DINSTALL_CREATE_DISTRIB=ON",
        # See opencv/CMakeLists.txt for options and defaults
        "-DBUILD_opencv_apps=OFF",
        "-DBUILD_SHARED_LIBS=OFF",
        "-DBUILD_TESTS=OFF",
        "-DBUILD_PERF_TESTS=OFF",
        "-DBUILD_DOCS=OFF",
        "-DOPENCV_EXTRA_MODULES_PATH=" +
        os.path.abspath("opencv_contrib/modules")
    ]

    # OS-specific components
    if (sys.platform == 'darwin'
            or sys.platform.startswith('linux')) and not build_headless:
        cmake_args.append("-DWITH_QT=4")

    if build_headless:
        # it seems that cocoa cannot be disabled so on macOS the package is not truly headless
        cmake_args.append("-DWITH_WIN32UI=OFF")
        cmake_args.append("-DWITH_QT=OFF")

    if sys.platform.startswith('linux'):
        cmake_args.append("-DWITH_V4L=ON")
        cmake_args.append("-DENABLE_PRECOMPILED_HEADERS=OFF")

        if all(v in os.environ for v in ('JPEG_INCLUDE_DIR', 'JPEG_LIBRARY')):
            cmake_args += [
                "-DBUILD_JPEG=OFF",
                "-DJPEG_INCLUDE_DIR=%s" % os.environ['JPEG_INCLUDE_DIR'],
                "-DJPEG_LIBRARY=%s" % os.environ['JPEG_LIBRARY']
            ]

    # Fixes for macOS builds
    if sys.platform == 'darwin':
        cmake_args.append(
            "-DWITH_LAPACK=OFF")  # Some OSX LAPACK fns are incompatible, see
        # https://github.com/skvark/opencv-python/issues/21
        cmake_args.append("-DCMAKE_CXX_FLAGS=-stdlib=libc++")

    if sys.platform.startswith('linux'):
        cmake_args.append(
            "-DWITH_IPP=OFF")  # tests fail with IPP compiled with
        # devtoolset-2 GCC 4.8.2 or vanilla GCC 4.9.4
        # see https://github.com/skvark/opencv-python/issues/138
    if sys.platform.startswith('linux') and not x64:
        cmake_args.append("-DCMAKE_CXX_FLAGS=-U__STRICT_ANSI__")

    # ABI config variables are introduced in PEP 425
    if sys.version_info[:2] < (3, 2):
        import warnings
        warnings.filterwarnings('ignore', r"Config variable '[^']+' is unset, "
                                r"Python ABI tag may be incorrect",
                                category=RuntimeWarning)
        del warnings

    # works via side effect
    RearrangeCMakeOutput(rearrange_cmake_output_data,
                         files_outside_package_dir, package_data.keys())

    skbuild.setup(
        name=package_name,
        version=package_version,
        url='https://github.com/skvark/opencv-python',
        license='MIT',
        description='Wrapper package for OpenCV python bindings.',
        long_description=long_description,
        long_description_content_type="text/markdown",
        packages=packages,
        package_data=package_data,
        maintainer="Olli-Pekka Heinisuo",
        include_package_data=True,
        ext_modules=EmptyListWithLength(),
        install_requires="numpy>=%s" % numpy_version,
        classifiers=[
            'Development Status :: 5 - Production/Stable',
            'Environment :: Console',
            'Intended Audience :: Developers',
            'Intended Audience :: Education',
            'Intended Audience :: Information Technology',
            'Intended Audience :: Science/Research',
            'License :: OSI Approved :: MIT License',
            'Operating System :: MacOS',
            'Operating System :: Microsoft :: Windows',
            'Operating System :: POSIX',
            'Operating System :: Unix',
            'Programming Language :: Python',
            'Programming Language :: Python :: 2',
            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.4',
            'Programming Language :: Python :: 3.5',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: C++',
            'Programming Language :: Python :: Implementation :: CPython',
            'Topic :: Scientific/Engineering',
            'Topic :: Scientific/Engineering :: Image Recognition',
            'Topic :: Software Development',
        ],
        cmake_args=cmake_args,
        cmake_source_dir=cmake_source_dir,
    )
Ejemplo n.º 40
0
import json
import platform
import sys
import sysconfig

metadata = {
    "major": sys.version_info.major,
    "minor": sys.version_info.minor,
    "abiflags": sysconfig.get_config_var("ABIFLAGS"),
    "interpreter": platform.python_implementation().lower(),
    "ext_suffix": sysconfig.get_config_var("EXT_SUFFIX"),
    "abi_tag": (sysconfig.get_config_var("SOABI") or "-").split("-")[1]
    or None,
    "m": sysconfig.get_config_var("WITH_PYMALLOC") == 1,
    "u": sysconfig.get_config_var("Py_UNICODE_SIZE") == 4,
    "d": sysconfig.get_config_var("Py_DEBUG") == 1,
    # This one isn't technically necessary, but still very useful for sanity checks
    "platform": sys.platform,
}

print(json.dumps(metadata))
Ejemplo n.º 41
0
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Utility script to genertae the python tag + the abi tag + platform tag for a Python

import distutils.util
import sys
import sysconfig

# TODO: pigweed virtualenv don't have pep425tags, will revisit it after figuring out with pigwee
# The below is temporary solution.
#from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag, get_platform
#print(get_abbr_impl() + get_impl_ver() + "-" + get_abi_tag() + "-" + get_platform())

abbr_ver = "cp"
impl_ver = str(sys.version_info[0]) + str(sys.version_info[1])
if sysconfig.get_config_var('SOABI') is None:
    abi_tag = abbr_ver + impl_ver
else:
    abi_tag = 'cp' + sysconfig.get_config_var('SOABI').split('-')[1]
platform_tag = distutils.util.get_platform().replace('.', '_').replace('-', '_')

print(abbr_ver + impl_ver + "-" + abi_tag + "-" + platform_tag)
Ejemplo n.º 42
0
    def get_python_include_dir(python_version):
        """Get include directory associated with the current python
        interpreter."""
        # determine python include dir
        python_include_dir = sysconfig.get_config_var('INCLUDEPY')

        # if Python.h not found (or python_include_dir is None), try to find a
        # suitable include dir
        found_python_h = (python_include_dir is not None or os.path.exists(
            os.path.join(python_include_dir, 'Python.h')))

        if not found_python_h:

            # NOTE(opadron): these possible prefixes must be guarded against
            # AttributeErrors and KeyErrors because they each can throw on
            # different platforms or even different builds on the same platform.
            include_py = sysconfig.get_config_var('INCLUDEPY')
            include_dir = sysconfig.get_config_var('INCLUDEDIR')
            include = None
            plat_include = None
            python_inc = None
            python_inc2 = None

            try:
                include = sysconfig.get_path('include')
            except (AttributeError, KeyError):
                pass

            try:
                plat_include = sysconfig.get_path('platinclude')
            except (AttributeError, KeyError):
                pass

            try:
                python_inc = sysconfig.get_python_inc()
            except AttributeError:
                pass

            if include_py is not None:
                include_py = os.path.dirname(include_py)
            if include is not None:
                include = os.path.dirname(include)
            if plat_include is not None:
                plat_include = os.path.dirname(plat_include)
            if python_inc is not None:
                python_inc2 = os.path.join(
                    python_inc, ".".join(map(str, sys.version_info[:2])))

            candidate_prefixes = list(
                filter(bool, (
                    include_py,
                    include_dir,
                    include,
                    plat_include,
                    python_inc,
                    python_inc2,
                )))

            candidate_versions = (python_version, )
            if python_version:
                candidate_versions += ('', )

            candidates = (os.path.join(prefix, ''.join(('python', ver)))
                          for (prefix, ver) in itertools.product(
                              candidate_prefixes, candidate_versions))

            for candidate in candidates:
                if os.path.exists(os.path.join(candidate, 'Python.h')):
                    # we found an include directory
                    python_include_dir = candidate
                    break

        # TODO(opadron): what happens if we don't find an include directory?
        #                Throw SKBuildError?

        return python_include_dir
Ejemplo n.º 43
0
    def test_ldshared_value(self):
        ldflags = sysconfig.get_config_var('LDFLAGS')
        ldshared = sysconfig.get_config_var('LDSHARED')

        self.assertIn(ldflags, ldshared)
Ejemplo n.º 44
0
#!/usr/bin/env python3
import re
import sys
import shutil
import os.path
import subprocess
import sysconfig

import reindent
import untabify

SRCDIR = sysconfig.get_config_var('srcdir')


def n_files_str(count):
    """Return 'N file(s)' with the proper plurality on 'file'."""
    return "{} file{}".format(count, "s" if count != 1 else "")


def status(message, modal=False, info=None):
    """Decorator to output status info to stdout."""
    def decorated_fxn(fxn):
        def call_fxn(*args, **kwargs):
            sys.stdout.write(message + ' ... ')
            sys.stdout.flush()
            result = fxn(*args, **kwargs)
            if not modal and not info:
                print("done")
            elif info:
                print(info(result))
            else:
Ejemplo n.º 45
0
def get_config_var(var):
    try:
        return sysconfig.get_config_var(var)
    except IOError as e:  # Issue #1074
        warnings.warn("{0}".format(e), RuntimeWarning)
        return None
Ejemplo n.º 46
0
except ImportError:             # python < 3.4
    try:
        from imp import cache_from_source
    except ImportError:         # python < 3.2
        def cache_from_source(path):
            root, ext = os.path.splitext(path)
            return root + '.pyc'

try:
    import sysconfig
except ImportError:            # pragma: NO COVER
    # python < 2.7
    # FIXME: incorrect on non-posix systems
    EXT_SUFFIX = '.so'
else:
    EXT_SUFFIX = (sysconfig.get_config_var('EXT_SUFFIX')
                  or sysconfig.get_config_var('SO'))


class file_cm(object):
    """ Add context manager methods to dumb file-like instances.

    """
    def __init__(self, fp):
        self._fp = fp

    def __enter__(self):
        return self._fp

    def __exit__(self, typ, inst, tb):
        self._fp.close()
Ejemplo n.º 47
0
        git_ver = get_version()
        git_num = int(git_ver.split('.')[3].split('+')[0].replace("dev", ""))
    except:
        git_num = None

include_dirs_numpy = [numpy.get_include()]
cc = None
if 'CC' in os.environ:
    if 'clang' in os.environ['CC']:
        cc = 'clang'
    if 'gcc' in os.environ['CC']:
        cc = 'gcc'

# Workaround Python issue 21121
import sysconfig
config_var = sysconfig.get_config_var("CFLAGS")
if config_var is not None and "-Werror=declaration-after-statement" in config_var:
    os.environ['CFLAGS'] = config_var.replace(
        "-Werror=declaration-after-statement", "")

######################
# _phonopy extension #
######################
include_dirs_phonopy = ['c/harmonic_h', 'c/kspclib_h'] + include_dirs_numpy
sources_phonopy = [
    'c/_phonopy.c', 'c/harmonic/dynmat.c', 'c/harmonic/derivative_dynmat.c',
    'c/kspclib/kgrid.c', 'c/kspclib/tetrahedron_method.c'
]

if with_openmp:
    extra_compile_args_phonopy = [
Ejemplo n.º 48
0
    print("Usage: {0} [{1}]".format(sys.argv[0],
                                    '|'.join('--' + opt
                                             for opt in valid_opts)),
          file=sys.stderr)
    sys.exit(code)


try:
    opts, args = getopt.getopt(sys.argv[1:], '', valid_opts)
except getopt.error:
    exit_with_usage()

if not opts:
    exit_with_usage()

pyver = sysconfig.get_config_var('VERSION')
getvar = sysconfig.get_config_var

opt_flags = [flag for (flag, val) in opts]

if '--help' in opt_flags:
    exit_with_usage(code=0)

for opt in opt_flags:
    if opt == '--prefix':
        print(sysconfig.get_config_var('prefix'))

    elif opt == '--exec-prefix':
        print(sysconfig.get_config_var('exec_prefix'))

    elif opt in ('--includes', '--cflags'):
Ejemplo n.º 49
0
    def test_attributes(self):
        self.assertIsInstance(sys.api_version, int)
        self.assertIsInstance(sys.argv, list)
        self.assertIn(sys.byteorder, ("little", "big"))
        self.assertIsInstance(sys.builtin_module_names, tuple)
        self.assertIsInstance(sys.copyright, str)
        self.assertIsInstance(sys.exec_prefix, str)
        self.assertIsInstance(sys.base_exec_prefix, str)
        self.assertIsInstance(sys.executable, str)
        self.assertEqual(len(sys.float_info), 11)
        self.assertEqual(sys.float_info.radix, 2)
        self.assertEqual(len(sys.int_info), 2)
        if test.support.check_impl_detail(cpython=True):
            self.assertTrue(sys.int_info.bits_per_digit % 5 == 0)
        else:
            self.assertTrue(sys.int_info.bits_per_digit >= 1)
        self.assertTrue(sys.int_info.sizeof_digit >= 1)
        self.assertEqual(type(sys.int_info.bits_per_digit), int)
        self.assertEqual(type(sys.int_info.sizeof_digit), int)
        self.assertIsInstance(sys.hexversion, int)

        if test.support.check_impl_detail(cpython=True):
            self.assertEqual(len(sys.hash_info), 9)
        self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width)
        # sys.hash_info.modulus should be a prime; we do a quick
        # probable primality test (doesn't exclude the possibility of
        # a Carmichael number)
        for x in range(1, 100):
            self.assertEqual(
                pow(x, sys.hash_info.modulus - 1, sys.hash_info.modulus), 1,
                "sys.hash_info.modulus {} is a non-prime".format(
                    sys.hash_info.modulus))
        self.assertIsInstance(sys.hash_info.inf, int)
        self.assertIsInstance(sys.hash_info.nan, int)
        self.assertIsInstance(sys.hash_info.imag, int)
        if test.support.check_impl_detail(cpython=True):
            algo = sysconfig.get_config_var("Py_HASH_ALGORITHM")
            if sys.hash_info.algorithm in {"fnv", "siphash24"}:
                self.assertIn(sys.hash_info.hash_bits, {32, 64})
                self.assertIn(sys.hash_info.seed_bits, {32, 64, 128})

                if algo == 1:
                    self.assertEqual(sys.hash_info.algorithm, "siphash24")
                elif algo == 2:
                    self.assertEqual(sys.hash_info.algorithm, "fnv")
                else:
                    self.assertIn(sys.hash_info.algorithm,
                                  {"fnv", "siphash24"})
            else:
                # PY_HASH_EXTERNAL
                self.assertEqual(algo, 0)
            self.assertGreaterEqual(sys.hash_info.cutoff, 0)
            self.assertLess(sys.hash_info.cutoff, 8)

        self.assertIsInstance(sys.maxsize, int)
        self.assertIsInstance(sys.maxunicode, int)
        self.assertEqual(sys.maxunicode, 0x10FFFF)
        self.assertIsInstance(sys.platform, str)
        self.assertIsInstance(sys.prefix, str)
        self.assertIsInstance(sys.base_prefix, str)
        self.assertIsInstance(sys.version, str)
        vi = sys.version_info
        self.assertIsInstance(vi[:], tuple)
        self.assertEqual(len(vi), 5)
        self.assertIsInstance(vi[0], int)
        self.assertIsInstance(vi[1], int)
        self.assertIsInstance(vi[2], int)
        self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
        self.assertIsInstance(vi[4], int)
        self.assertIsInstance(vi.major, int)
        self.assertIsInstance(vi.minor, int)
        self.assertIsInstance(vi.micro, int)
        self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
        self.assertIsInstance(vi.serial, int)
        self.assertEqual(vi[0], vi.major)
        self.assertEqual(vi[1], vi.minor)
        self.assertEqual(vi[2], vi.micro)
        self.assertEqual(vi[3], vi.releaselevel)
        self.assertEqual(vi[4], vi.serial)
        self.assertTrue(vi > (1, 0, 0))
        self.assertIsInstance(sys.float_repr_style, str)
        self.assertIn(sys.float_repr_style, ('short', 'legacy'))
        if not sys.platform.startswith('win'):
            self.assertIsInstance(sys.abiflags, str)
Ejemplo n.º 50
0
import sys
import sysconfig
import warnings
import numpy as nu
import ctypes
import ctypes.util
from numpy.ctypeslib import ndpointer
import os
from galpy import potential, potential_src
from galpy.util import galpyWarning
#Find and load the library
_lib = None
outerr = None
PY3 = sys.version > '3'
if PY3:  #pragma: no cover
    _ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
else:
    _ext_suffix = '.so'
for path in sys.path:
    try:
        _lib = ctypes.CDLL(
            os.path.join(path, 'galpy_integrate_c%s' % _ext_suffix))
    except OSError as e:
        if os.path.exists(
                os.path.join(path, 'galpy_integrate_c%s' %
                             _ext_suffix)):  #pragma: no cover
            outerr = e
        _lib = None
    else:
        break
if _lib is None:  #pragma: no cover
Ejemplo n.º 51
0
def init_env(debug=False,
             sanitize=False,
             native_optimizations=True,
             profile=False):
    global cflags, ldflags, cc, ldpaths
    native_optimizations = native_optimizations and not sanitize and not debug
    cc, ccver = cc_version()
    print('CC:', cc, ccver)
    stack_protector = '-fstack-protector'
    if ccver >= (4, 9) and cc == 'gcc':
        stack_protector += '-strong'
    missing_braces = ''
    if ccver < (5, 2) and cc == 'gcc':
        missing_braces = '-Wno-missing-braces'
    optimize = '-g3' if debug or sanitize else '-O3'
    sanitize_args = get_sanitize_args(cc, ccver) if sanitize else set()
    cflags = os.environ.get('OVERRIDE_CFLAGS', (
        '-Wextra -Wno-missing-field-initializers -Wall -std=c99 -D_XOPEN_SOURCE=700'
        ' -pedantic-errors -Werror {} {} -D{}DEBUG -fwrapv {} {} -pipe {} -fvisibility=hidden'
    ).format(
        optimize,
        ' '.join(sanitize_args),
        ('' if debug else 'N'),
        stack_protector,
        missing_braces,
        '-march=native' if native_optimizations else '',
    ))
    cflags = shlex.split(cflags) + shlex.split(
        sysconfig.get_config_var('CCSHARED'))
    ldflags = os.environ.get(
        'OVERRIDE_LDFLAGS',
        '-Wall ' + ' '.join(sanitize_args) + ('' if debug else ' -O3'))
    ldflags = shlex.split(ldflags)
    cflags += shlex.split(os.environ.get('CFLAGS', ''))
    ldflags += shlex.split(os.environ.get('LDFLAGS', ''))
    if not debug and not sanitize:
        # See https://github.com/google/sanitizers/issues/647
        cflags.append('-flto'), ldflags.append('-flto')

    if profile:
        cflags.append('-DWITH_PROFILER')
        cflags.append('-g3')
        ldflags.append('-lprofiler')
    cflags.append('-pthread')
    # We add 4000 to the primary version because vim turns on SGR mouse mode
    # automatically if this version is high enough
    cflags.append('-DPRIMARY_VERSION={}'.format(version[0] + 4000))
    cflags.append('-DSECONDARY_VERSION={}'.format(version[1]))
    if not is_travis and not isosx:
        at_least_version('glew', 2)
    cflags.extend(pkg_config('libpng', '--cflags-only-I'))
    if not isosx:
        cflags.extend(pkg_config('glew', '--cflags-only-I'))
    if isosx:
        font_libs = ['-framework', 'CoreText', '-framework', 'CoreGraphics']
    else:
        cflags.extend(pkg_config('fontconfig', '--cflags-only-I'))
        font_libs = pkg_config('fontconfig', '--libs')
        cflags.extend(pkg_config('harfbuzz', '--cflags-only-I'))
        font_libs.extend(pkg_config('harfbuzz', '--libs'))
    cflags.extend(pkg_config('glfw3', '--cflags-only-I'))
    ldflags.append('-shared')
    pylib = get_python_flags(cflags)
    if isosx:
        glfw_ldflags = pkg_config('--libs', '--static',
                                  'glfw3') + ['-framework', 'OpenGL']
        glew_libs = []
    else:
        glfw_ldflags = pkg_config('glfw3', '--libs')
        glew_libs = pkg_config('glew', '--libs')
    libpng = pkg_config('libpng', '--libs')
    ldpaths = pylib + glew_libs + font_libs + glfw_ldflags + libpng + [
        '-lunistring'
    ]
    if not isosx:
        ldpaths += ['-lrt']
    if '-lz' not in ldpaths:
        ldpaths.append('-lz')

    try:
        os.mkdir(build_dir)
    except FileExistsError:
        pass
Ejemplo n.º 52
0
def _generic_abi():
    # type: () -> Iterator[str]
    abi = sysconfig.get_config_var("SOABI")
    if abi:
        yield _normalize_string(abi)
Ejemplo n.º 53
0
 if sys.version_info[0] == 2:
   # python 2 seems to have hoc.__file__ already filled in so never get here.
   try:
     import imp
     mspec = imp.find_module("neuron")
     origin = mspec[1]
   except:
     pass
 else:
   from importlib import util
   mspec = util.find_spec("neuron")
   if mspec:
     origin = mspec.origin
 if origin is not None:
   import sysconfig
   hoc_path = origin.rstrip("__init__.py") + "hoc" + sysconfig.get_config_var('SO')
   setattr(hoc, "__file__", hoc_path)
 else:
   # if the above is robust, maybe all this can be removed.
   # next try is to derive from nrnversion(6) (only works for autotools build)
   import platform
   import os
   p = h.nrnversion(6)
   if "--prefix=" in p:
     p = p[p.find('--prefix=') + 9:]
     p = p[:p.find("'")]
   else:
     p = "/usr/local/nrn"
   if sys.version_info >= (3, 0):
     import sysconfig
     hoc_path = p + "/lib/python/neuron/hoc%s" % sysconfig.get_config_var('SO')
Ejemplo n.º 54
0
 def test_osx_ext_suffix(self):
     suffix = sysconfig.get_config_var('EXT_SUFFIX')
     self.assertTrue(suffix.endswith('-darwin.so'), suffix)
Ejemplo n.º 55
0
"""Provide access to Python's configuration information.  The specific
configuration variables available depend heavily on the platform and
configuration.  The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys().  Additional convenience functions are also
available.

Written by:   Fred L. Drake, Jr.
Email:        <*****@*****.**>
"""

import _imp
import os
import re
import sys
import warnings

from functools import partial

from .errors import DistutilsPlatformError

from sysconfig import (
    _PREFIX as PREFIX,
    _BASE_PREFIX as BASE_PREFIX,
    _EXEC_PREFIX as EXEC_PREFIX,
    _BASE_EXEC_PREFIX as BASE_EXEC_PREFIX,
    _PROJECT_BASE as project_base,
    _PYTHON_BUILD as python_build,
    _init_posix as sysconfig_init_posix,
    parse_config_h as sysconfig_parse_config_h,
Ejemplo n.º 56
0
 def test_SO_value(self):
     with check_warnings(('', DeprecationWarning)):
         self.assertEqual(sysconfig.get_config_var('SO'),
                          sysconfig.get_config_var('EXT_SUFFIX'))
Ejemplo n.º 57
0
import enum
import locale
import math
import platform
import sys
import sysconfig
import time
import threading
import unittest
try:
    import _testcapi
except ImportError:
    _testcapi = None

# Max year is only limited by the size of C int.
SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900

SEC_TO_US = 10**6
US_TO_NS = 10**3
MS_TO_NS = 10**6
SEC_TO_NS = 10**9
NS_TO_SEC = 10**9


class _PyTime(enum.IntEnum):
    # Round towards minus infinity (-inf)
    ROUND_FLOOR = 0
    # Round towards infinity (+inf)
    ROUND_CEILING = 1
Ejemplo n.º 58
0
def test_generic_interpreter():
    version = sysconfig.get_config_var("py_version_nodot")
    if not version:
        version = "".join(sys.version_info[:2])
    result = tags._generic_interpreter("sillywalk", sys.version_info[:2])
    assert result == "sillywalk{version}".format(version=version)
Ejemplo n.º 59
0
                           "language_level":3}

cmodules = {
    "btom.cmain.py_base_atom":["btom/cmain/py_base_atom.pyx",\
                                "btom/cmain/c_base_atom.cpp"]
}

cextensions = cythonize([Extension(k,v,language="c++",\
                                   include_dirs=["btom/cmain",numpy.get_include()],\
                                   extra_compile_args=["-std=c++11","-DPARALLEL"])\
                         for k,v in cmodules.items()])

import os

os.environ["CFLAGS"] = " ".join([
    u for u in sysconfig.get_config_var("CFLAGS").split(" ")
    if "xHost" not in u
])
os.environ["CC"] = mpi4py.get_config()["mpicc"]

setup(name="btom",
        namespace_packages=["btom"],
        version='0.1',
        url='http://notset/jet',
        author="Lukas Linhart",
        author_email="*****@*****.**",
        license='None',
        ext_modules =cythonize(extensions)+cextensions, #+int_modules+cextensions,\
        packages=find_packages(),\
        zip_safe=False,\
        include_package_data=True)
Ejemplo n.º 60
0
def pythonlib_dir():
    """return path where libpython* is."""
    if sys.platform == 'win32':
        return os.path.join(sys.prefix, "libs")
    else:
        return get_config_var('LIBDIR')