Example #1
0
    def __enter__(self):
        self.save_path = os.environ.get('PATH', None)
        self.save_pythonpath = os.environ.get('PYTHONPATH', None)
        self.save_nousersite = os.environ.get('PYTHONNOUSERSITE', None)

        install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'
        install_dirs = get_paths(install_scheme, vars={
            'base': self.path,
            'platbase': self.path,
        })

        scripts = install_dirs['scripts']
        if self.save_path:
            os.environ['PATH'] = scripts + os.pathsep + self.save_path
        else:
            os.environ['PATH'] = scripts + os.pathsep + os.defpath

        # Note: prefer distutils' sysconfig to get the
        # library paths so PyPy is correctly supported.
        purelib = get_python_lib(plat_specific=0, prefix=self.path)
        platlib = get_python_lib(plat_specific=1, prefix=self.path)
        if purelib == platlib:
            lib_dirs = purelib
        else:
            lib_dirs = purelib + os.pathsep + platlib
        if self.save_pythonpath:
            os.environ['PYTHONPATH'] = lib_dirs + os.pathsep + \
                self.save_pythonpath
        else:
            os.environ['PYTHONPATH'] = lib_dirs

        os.environ['PYTHONNOUSERSITE'] = '1'

        return self.path
Example #2
0
 def __init__(self):
     self.os = platform.system()
     self.check_permission()
     self.cwd = os.getcwd()
     if self.os == 'Windows': self.cwd = os.getcwd().replace('\\', '/')
     self.needed_execs = ('pyuic4', 'pylupdate4', 'lrelease-qt4')
     self.vars = {
         'Linux': {
             'data': '/usr/share/qt-project-creator',
             'bin': '/usr/bin',
             'docs': '/usr/share/doc/qt-project-creator',
             'package': os.path.join(get_python_lib(), 'qtprojectcreator'),
             'lib': get_python_lib(),
             'exec': '/usr/bin/qt-project-creator.py'
         },
         'Windows': {
             'data': 'C:/Program Files/qt-project-creator/data',
             'docs': 'C:/Program Files/qt-project-creator/docs',
             'bin': 'C:/Program Files/qt-project-creator/bin',
             'exec': 'C:/Program Files/qt-project-creator/bin/qt-project-creator.py',
             'package': os.path.join(get_python_lib(), 'qtprojectcreator').replace('\\', '/'),
             'lib': get_python_lib().replace('\\', '/'),
         }
     }
     self.all_paths = (self.vars[self.os]['data'], self.vars[self.os]['docs'], \
                 self.vars[self.os]['package'], self.vars[self.os]['exec']
     )
Example #3
0
def main():
  if sys.platform == 'win32':
    shutil.rmtree('%s\\pacparser' % sysconfig.get_python_lib(),
                  ignore_errors=True)
    shutil.copytree('pacparser', '%s\\pacparser' % sysconfig.get_python_lib())
  else:
    print('This script should be used only on Win32 systems.')
Example #4
0
def main():
    here = path.abspath(path.dirname(__file__))
    print("Copying 'emoji.pth' to %s" % get_python_lib())
    copyfile(
        path.join(here, 'emoji.pth'),
        path.join(get_python_lib(), 'emoji.pth')
    )
Example #5
0
 def minimum_path(cls):
   """
     Return as a tuple the emulated sys.path and sys.path_importer_cache of
     a bare python installation, a la python -S.
   """
   from site import USER_SITE
   from twitter.common.collections import OrderedSet
   from pkg_resources import find_distributions
   from distutils.sysconfig import get_python_lib
   site_libs = set([get_python_lib(plat_specific=False), get_python_lib(plat_specific=True)])
   site_distributions = OrderedSet()
   for path_element in sys.path:
     if any(path_element.startswith(site_lib) for site_lib in site_libs):
       TRACER.log('Inspecting path element: %s' % path_element)
       site_distributions.update(dist.location for dist in find_distributions(path_element))
   user_site_distributions = OrderedSet(dist.location for dist in find_distributions(USER_SITE))
   for path in site_distributions:
     TRACER.log('Scrubbing from site-packages: %s' % path)
   for path in user_site_distributions:
     TRACER.log('Scrubbing from user site: %s' % path)
   scrub_paths = site_distributions | user_site_distributions
   scrubbed_sys_path = list(OrderedSet(sys.path) - scrub_paths)
   scrub_from_importer_cache = filter(
     lambda key: any(key.startswith(path) for path in scrub_paths),
     sys.path_importer_cache.keys())
   scrubbed_importer_cache = dict((key, value) for (key, value) in sys.path_importer_cache.items()
     if key not in scrub_from_importer_cache)
   return scrubbed_sys_path, scrubbed_importer_cache
Example #6
0
    def run(self):
        install_system=platform.system();
        path_to_charm2 = None;
        if install_system == 'Darwin':
            path_to_charm = get_python_lib();
        elif install_system == 'Windows':
            path_to_charm = get_python_lib();
        elif install_system == 'Linux':
            dist = platform.linux_distribution()[0];
            if dist == 'Ubuntu' or dist == 'debian' or dist == 'LinuxMint':
                path_to_charm = get_python_lib(1, 1, '/usr/local') + '/dist-packages';
                path_to_charm2 = get_python_lib(1, 1, '/usr/local') + '/site-packages';
            elif dist == 'Fedora':
                path_to_charm = get_python_lib(1, 1, '/usr') + '/site-packages';
        #print('python path =>', path_to_charm, _charm_version);
        shutil.rmtree(path_to_charm+'/__pycache__', True)
        shutil.rmtree(path_to_charm+'/compiler', True)
        shutil.rmtree(path_to_charm+'/schemes', True)
        shutil.rmtree(path_to_charm+'/toolbox', True)
        shutil.rmtree(path_to_charm+'/charm/engine', True)

        for files in os.listdir(path_to_charm):
            if not re.match('Charm_Crypto-'+_charm_version+'\.egg-info', files) and re.match('Charm_Crypto-.*\.egg-info', files):
                #print(path_to_charm+'/'+files)
                os.remove(path_to_charm+'/'+files)

        for files in os.listdir(path_to_charm+'/charm'):
            if re.match('.*\.so$', files):
                #print(path_to_charm+'/charm/'+files)
                os.remove(path_to_charm+'/charm/'+files)
Example #7
0
def get_framework_python_dir_windows( vDictArgs ):
	dbg = utilsDebug.CDebugFnVerbose( "Python script get_framework_python_dir_windows()" );
	bOk = True;
	strWkDir = "";
	strErrMsg = "";
	 
	# We are being built by LLVM, so use the PYTHON_INSTALL_DIR argument,
	# and append the python version directory to the end of it.  Depending 
	# on the system other stuff may need to be put here as well.
	from distutils.sysconfig import get_python_lib;
	strPythonInstallDir = "";
	bHaveArgPrefix = vDictArgs.has_key( "--prefix" );
	if bHaveArgPrefix: 
		strPythonInstallDir = vDictArgs[ "--prefix" ];

	bHaveArgCmakeBuildConfiguration = vDictArgs.has_key( "--cmakeBuildConfiguration" );
	if bHaveArgCmakeBuildConfiguration:
		strPythonInstallDir += '/' + vDictArgs[ "--cmakeBuildConfiguration" ];

	if strPythonInstallDir.__len__() != 0:
		strWkDir = get_python_lib( True, False, strPythonInstallDir );
	else:
		strWkDir = get_python_lib( True, False );
	strWkDir += "/lldb";
	strWkDir = os.path.normcase( strWkDir );
	
	return (bOk, strWkDir, strErrMsg);
Example #8
0
def set_platform_directories():
    """Initialise the global variables relating to platform specific
    directories.
    """
    global plat_py_site_dir, plat_py_inc_dir, plat_py_conf_inc_dir
    global plat_bin_dir, plat_py_lib_dir, plat_sip_dir

    # We trust distutils for some stuff.
    plat_py_site_dir = sysconfig.get_python_lib(plat_specific=1)
    plat_py_inc_dir = sysconfig.get_python_inc()
    plat_py_conf_inc_dir = os.path.dirname(sysconfig.get_config_h_filename())

    if sys.platform == "win32":
        if sysconfig.python_build:
            try:
                plat_py_lib_dir = sysconfig.project_base + '\\PCBuild'
            except AttributeError:
                plat_py_lib_dir = sysconfig.get_python_inc() + '\\..\\pcbuild'
        else:
            plat_py_lib_dir = sys.prefix + "\\libs"
        plat_bin_dir = sys.exec_prefix
        plat_sip_dir = sys.prefix + "\\sip"
    else:
        lib_dir = sysconfig.get_python_lib(plat_specific=1, standard_lib=1)

        plat_py_lib_dir = lib_dir + "/config"
        plat_bin_dir = sys.exec_prefix + "/bin"
        plat_sip_dir = sys.prefix + "/share/sip"
 def test_get_python_lib(self):
     lib_dir = sysconfig.get_python_lib()
     # XXX doesn't work on Linux when Python was never installed before
     #self.assertTrue(os.path.isdir(lib_dir), lib_dir)
     # test for pythonxx.lib?
     self.assertNotEqual(sysconfig.get_python_lib(),
                         sysconfig.get_python_lib(prefix=TESTFN))
Example #10
0
def get_framework_python_dir_windows(vDictArgs):
    dbg = utilsDebug.CDebugFnVerbose(
        "Python script get_framework_python_dir_windows()")
    bOk = True
    strWkDir = ""
    strErrMsg = ""

    # We are being built by LLVM, so use the PYTHON_INSTALL_DIR argument,
    # and append the python version directory to the end of it.  Depending
    # on the system other stuff may need to be put here as well.
    from distutils.sysconfig import get_python_lib
    strPythonInstallDir = ""
    bHaveArgPrefix = "--prefix" in vDictArgs
    if bHaveArgPrefix:
        strPythonInstallDir = os.path.normpath(vDictArgs["--prefix"])

    bHaveArgCmakeBuildConfiguration = "--cmakeBuildConfiguration" in vDictArgs
    if bHaveArgCmakeBuildConfiguration:
        strPythonInstallDir = os.path.join(
            strPythonInstallDir,
            vDictArgs["--cmakeBuildConfiguration"])

    if strPythonInstallDir.__len__() != 0:
        strWkDir = get_python_lib(True, False, strPythonInstallDir)
    else:
        strWkDir = get_python_lib(True, False)
    strWkDir = os.path.normcase(os.path.join(strWkDir, "lldb"))

    return (bOk, strWkDir, strErrMsg)
Example #11
0
def set_platform_directories():
    """Initialise the global variables relating to platform specific
    directories.
    """
    global plat_py_site_dir, plat_py_inc_dir, plat_py_conf_inc_dir
    global plat_bin_dir, plat_py_lib_dir, plat_sip_dir

    # We trust distutils for some stuff.
    if os.environ.get("CROSS_COMPILE") == "yes":
        ketlaer = os.environ.get("KETLAER")
        plat_py_site_dir = ketlaer + "/lib/python2.6/site-packages"
        plat_py_inc_dir = ketlaer + "/include/python2.6"
        plat_py_conf_inc_dir = ketlaer + "/include/python2.6"
    else:
        plat_py_site_dir = sysconfig.get_python_lib(plat_specific=1)
        plat_py_inc_dir = sysconfig.get_python_inc()
        plat_py_conf_inc_dir = os.path.dirname(sysconfig.get_config_h_filename())

    if sys.platform == "win32":
        plat_py_lib_dir = sys.prefix + "\\libs"
        plat_bin_dir = sys.exec_prefix
        plat_sip_dir = sys.prefix + "\\sip"
    else:
        if os.environ.get("CROSS_COMPILE") == "yes":
            lib_dir = ketlaer + "/python/lib/python2.6"
        else:
            lib_dir = sysconfig.get_python_lib(plat_specific=1, standard_lib=1)

        plat_py_lib_dir = lib_dir + "/config"
        plat_bin_dir = sys.exec_prefix + "/bin"
        plat_sip_dir = sys.prefix + "/share/sip"
Example #12
0
def get_python_module_path(options):
    """Returns the location where the lldb Python module should be placed.

    @param options dictionary of options parsed from the command line.

    @return the directory where the lldb module should be placed.
    """
    if options.framework:
        # Caller wants to use the OS X framework packaging.

        # We are packaging in an OS X-style framework bundle. The
        # module dir will be within the
        # LLDB.framework/Resources/Python subdirectory.
        return os.path.join(
            options.target_dir,
            "LLDB.framework",
            "Resources",
            "Python",
            "lldb")
    else:
        from distutils.sysconfig import get_python_lib

        if options.prefix is not None:
            module_path = get_python_lib(True, False, options.prefix)
        else:
            module_path = get_python_lib(True, False)
        return os.path.normcase(
            os.path.join(module_path, "lldb"))
Example #13
0
def get_existing_pip_installation():
    """ returns current pip installation path """
    if run("pip freeze|grep confine-controller", err_codes=[0,1]).return_code == 0:
        for lib_path in get_python_lib(), get_python_lib(prefix="/usr/local"):
            existing_path = os.path.abspath(os.path.join(lib_path, "controller"))
            if os.path.exists(existing_path):
                return existing_path
    return None
Example #14
0
File: pex.py Project: Houzz/pex
 def site_libs(cls):
     site_libs = cls._get_site_packages()
     site_libs.update([sysconfig.get_python_lib(plat_specific=False), sysconfig.get_python_lib(plat_specific=True)])
     # On windows getsitepackages() returns the python stdlib too.
     if sys.prefix in site_libs:
         site_libs.remove(sys.prefix)
     real_site_libs = set(os.path.realpath(path) for path in site_libs)
     return site_libs | real_site_libs
def get_existing_pip_installation():
    """ returns current pip installation path """
    if run("pip freeze|grep django-orchestra", valid_codes=(0,1)).exit_code == 0:
        for lib_path in get_python_lib(), get_python_lib(prefix="/usr/local"):
            existing_path = os.path.abspath(os.path.join(lib_path, "orchestra"))
            if os.path.exists(existing_path):
                return existing_path
    return None
Example #16
0
 def _site_libs(cls):
   try:
     from site import getsitepackages
     site_libs = set(getsitepackages())
   except ImportError:
     site_libs = set()
   site_libs.update([sysconfig.get_python_lib(plat_specific=False),
                     sysconfig.get_python_lib(plat_specific=True)])
   return site_libs
Example #17
0
def setup_variables():
    add_path("LD_LIBRARY_PATH", config.lib_dir)
    add_path("PATH", config.bin_dir)

    add_path("XCURSOR_PATH",
             os.path.join(config.share_dir, "icons"))
    add_path("PKG_CONFIG_PATH",
             os.path.join(config.lib_dir, "pkgconfig"))
    add_path("PYTHONPATH",
             sysconfig.get_python_lib(prefix=config.install_dir))
    add_path("PYTHONPATH",
             sysconfig.get_python_lib(prefix=config.install_dir,
                                      plat_specific=True))
    add_path("PYTHONPATH",
             os.path.dirname(os.path.dirname(__file__)))

    add_path("ACLOCAL_PATH", "/usr/share/aclocal")
    add_path("ACLOCAL_FLAGS", "-I /usr/share/aclocal")

    add_path("XDG_DATA_DIRS", "/usr/share")
    add_path("XDG_DATA_DIRS", config.share_dir)

    add_path("XDG_CONFIG_DIRS", "/etc/xdg")
    add_path("XDG_CONFIG_DIRS", os.path.join(config.etc_dir, "xdg"))

    for system_lib_dir in config.system_lib_dirs:
        modules_path = os.path.join(system_lib_dir, "gio", "modules")
        if os.path.exists(modules_path):
            add_path("GIO_EXTRA_MODULES", modules_path)

        typelib_path = os.path.join(system_lib_dir, "girepository-1.0")
        if os.path.exists(typelib_path):
            add_path("GI_TYPELIB_PATH", typelib_path)

    add_path("GI_TYPELIB_PATH",
             os.path.join(config.lib_dir, "girepository-1.0"))

    os.environ["GTK_DATA_PREFIX"] = config.install_dir
    os.environ["GTK_PATH"] = os.path.join(config.lib_dir, "gtk-2.0")
    os.environ["CC"] = "ccache gcc"
    os.environ["CXX"] = "ccache g++"

    os.environ["GCONF_DEFAULT_SOURCE_PATH"] = _get_gconf_path()
    os.environ["GCONF_SCHEMA_INSTALL_SOURCE"] = \
        "xml:merged:" + os.path.join(_get_gconf_dir(), "gconf.xml.defaults")

    cache_home_dir = os.path.join(config.home_dir, "cache")
    utils.ensure_dir(cache_home_dir)
    os.environ["XDG_CACHE_HOME"] = cache_home_dir

    data_home_dir = os.path.join(config.home_dir, "data")
    utils.ensure_dir(data_home_dir)
    os.environ["XDG_DATA_HOME"] = data_home_dir

    config_home_dir = os.path.join(config.home_dir, "config")
    utils.ensure_dir(config_home_dir)
    os.environ["XDG_CONFIG_HOME"] = config_home_dir
 def test_get_python_lib(self):
     lib_dir = sysconfig.get_python_lib()
     # XXX doesn't work on Linux when Python was never installed before
     # self.assertTrue(os.path.isdir(lib_dir), lib_dir)
     # test for pythonxx.lib?
     self.assertNotEqual(sysconfig.get_python_lib(), sysconfig.get_python_lib(prefix=TESTFN))
     _sysconfig = __import__("sysconfig")
     res = sysconfig.get_python_lib(True, True)
     self.assertEqual(_sysconfig.get_path("platstdlib"), res)
Example #19
0
def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('models', parent_package, top_path)

    include = os.path.join(get_python_lib(), 'compmech', 'include')
    lib = os.path.join(get_python_lib(), 'compmech', 'lib')

    if os.name == 'nt':
        runtime_library_dirs = None
        if os.environ.get('CONDA_DEFAULT_ENV') is not None:
            #NOTE removing openmp to compile in MiniConda
            args_linear = ['-O0']
            args_nonlinear = ['-O0']
        else:
            args_linear = ['/openmp']
            args_nonlinear = ['/openmp', '/fp:fast']
    else:
        runtime_library_dirs = [lib]
        if os.environ.get('CONDA_DEFAULT_ENV') is not None:
            #NOTE removing openmp to compile in MiniConda
            args_linear = ['-O0']
            args_nonlinear = ['-O0']
        else:
            args_linear = ['-fopenmp']
            args_nonlinear = ['-fopenmp', '-ffast-math']

    config.add_extension('bladestiff1d_clt_donnell_bardell',
                     ['bladestiff1d_clt_donnell_bardell.pyx'],
                     extra_compile_args=args_linear,
                     runtime_library_dirs=runtime_library_dirs,
                     include_dirs=[include],
                     libraries=['bardell_functions', 'bardell'],
                     library_dirs=[lib])

    config.add_extension('bladestiff2d_clt_donnell_bardell',
                     ['bladestiff2d_clt_donnell_bardell.pyx'],
                     extra_compile_args=args_linear,
                     runtime_library_dirs=runtime_library_dirs,
                     include_dirs=[include],
                     libraries=['bardell_functions', 'bardell'],
                     library_dirs=[lib])

    config.add_extension('tstiff2d_clt_donnell_bardell',
                     ['tstiff2d_clt_donnell_bardell.pyx'],
                     extra_compile_args=args_linear,
                     runtime_library_dirs=runtime_library_dirs,
                     include_dirs=[include],
                     libraries=['bardell_functions', 'bardell',
                         'bardell_12', 'bardell_c0c1'],
                     library_dirs=[lib])

    cythonize(config.ext_modules)

    config.make_config_py()

    return config
Example #20
0
def get_pth_path_for_module(module_name_full):
    """ Splits module name full into module name and version """
    name, version = get_module_name_version(module_name_full)
    if not version:
        # Only module name is specified
        pth_file_name = os.path.join(get_python_lib(), name+".pth")
    else:
        # Module name and verion are specified
        pth_file_name = os.path.join(get_python_lib(), name+"-"+version+".pth")
    return pth_file_name
Example #21
0
def getDataFiles():
   import sys
   if sys.platform.startswith( "win" ):
      return [( get_python_lib(), [ "DUOLib.dll" ] )]
   elif sys.platform.startswith( "linux" ):
      return [( get_python_lib(), [ "libDUO.so" ] )]
   elif sys.platform.startswith( "dawrin" ):
      return [( get_python_lib(), [ "libDUO.dylib" ] )]
   else:
      return None
Example #22
0
    def __init__(self):
        # type: () -> None
        self._temp_dir = TempDirectory(kind="build-env")
        self._temp_dir.create()

        self._prefixes = OrderedDict((
            (name, _Prefix(os.path.join(self._temp_dir.path, name)))
            for name in ('normal', 'overlay')
        ))

        self._bin_dirs = []  # type: List[str]
        self._lib_dirs = []  # type: List[str]
        for prefix in reversed(list(self._prefixes.values())):
            self._bin_dirs.append(prefix.bin_dir)
            self._lib_dirs.extend(prefix.lib_dirs)

        # Customize site to:
        # - ensure .pth files are honored
        # - prevent access to system site packages
        system_sites = {
            os.path.normcase(site) for site in (
                get_python_lib(plat_specific=False),
                get_python_lib(plat_specific=True),
            )
        }
        self._site_dir = os.path.join(self._temp_dir.path, 'site')
        if not os.path.exists(self._site_dir):
            os.mkdir(self._site_dir)
        with open(os.path.join(self._site_dir, 'sitecustomize.py'), 'w') as fp:
            fp.write(textwrap.dedent(
                '''
                import os, site, sys

                # First, drop system-sites related paths.
                original_sys_path = sys.path[:]
                known_paths = set()
                for path in {system_sites!r}:
                    site.addsitedir(path, known_paths=known_paths)
                system_paths = set(
                    os.path.normcase(path)
                    for path in sys.path[len(original_sys_path):]
                )
                original_sys_path = [
                    path for path in original_sys_path
                    if os.path.normcase(path) not in system_paths
                ]
                sys.path = original_sys_path

                # Second, add lib directories.
                # ensuring .pth file are processed.
                for path in {lib_dirs!r}:
                    assert not path in sys.path
                    site.addsitedir(path)
                '''
            ).format(system_sites=system_sites, lib_dirs=self._lib_dirs))
Example #23
0
def data_files():
    """Build list of data files to be installed"""
    files = []
    if os.name == "nt":
        os.chdir("bin")
        for (dp, dn, names) in os.walk("addons"):
            files.append((dp, map(lambda x: join("bin", dp, x), names)))
        os.chdir("..")
        # for root, _, names in os.walk(join('bin','addons')):
        #    files.append((root, [join(root, name) for name in names]))
        for root, _, names in os.walk("doc"):
            files.append((root, [join(root, name) for name in names]))
        # for root, _, names in os.walk('pixmaps'):
        #    files.append((root, [join(root, name) for name in names]))
        files.append((".", [join("bin", "import_xml.rng")]))
    else:
        man_directory = join("share", "man")
        files.append((join(man_directory, "man1"), ["man/openerp-server.1"]))
        files.append((join(man_directory, "man5"), ["man/openerp_serverrc.5"]))

        doc_directory = join("share", "doc", "openerp-server-%s" % version)
        files.append((doc_directory, filter(isfile, glob.glob("doc/*"))))
        files.append(
            (join(doc_directory, "migrate", "3.3.0-3.4.0"), filter(isfile, glob.glob("doc/migrate/3.3.0-3.4.0/*")))
        )
        files.append(
            (join(doc_directory, "migrate", "3.4.0-4.0.0"), filter(isfile, glob.glob("doc/migrate/3.4.0-4.0.0/*")))
        )

        openerp_site_packages = join(get_python_lib(prefix=""), "openerp-server")

        files.append((openerp_site_packages, [join("bin", "import_xml.rng")]))

        if sys.version_info[0:2] == (2, 5):
            files.append(
                (
                    openerp_site_packages,
                    [
                        join("python25-compat", "BaseHTTPServer.py"),
                        join("python25-compat", "SimpleXMLRPCServer.py"),
                        join("python25-compat", "SocketServer.py"),
                    ],
                )
            )

        for addonname, add_path in find_addons():
            addon_path = join(get_python_lib(prefix=""), "openerp-server", "addons", addonname)
            for root, dirs, innerfiles in os.walk(add_path):
                innerfiles = filter(lambda fil: os.path.splitext(fil)[1] not in (".pyc", ".pyd", ".pyo"), innerfiles)
                if innerfiles:
                    res = os.path.normpath(join(addon_path, root.replace(join(add_path), ".")))
                    files.extend(((res, map(lambda fil: join(root, fil), innerfiles)),))

    return files
Example #24
0
def main():
    server = config.Config().get_musicbrainz_server()
    musicbrainzngs.set_hostname(server)

    # Find whipper's plugins paths (local paths have higher priority)
    plugins_p = [directory.data_path('plugins')]  # local path (in $HOME)
    if hasattr(sys, 'real_prefix'):  # no getsitepackages() in virtualenv
        plugins_p.append(
            get_python_lib(plat_specific=False, standard_lib=False,
                           prefix='/usr/local') + '/whipper/plugins')
        plugins_p.append(get_python_lib(plat_specific=False,
                         standard_lib=False) + '/whipper/plugins')
    else:
        plugins_p += [x + '/whipper/plugins' for x in site.getsitepackages()]

    # register plugins with pkg_resources
    distributions, _ = pkg_resources.working_set.find_plugins(
        pkg_resources.Environment(plugins_p)
    )
    list(map(pkg_resources.working_set.add, distributions))
    try:
        cmd = Whipper(sys.argv[1:], os.path.basename(sys.argv[0]), None)
        ret = cmd.do()
    except SystemError as e:
        logger.critical("SystemError: %s", e)
        if (isinstance(e, common.EjectError) and
                cmd.options.eject in ('failure', 'always')):
            eject_device(e.device)
        return 255
    except RuntimeError as e:
        print(e)
        return 1
    except KeyboardInterrupt:
        return 2
    except ImportError as e:
        raise
    except task.TaskException as e:
        if isinstance(e.exception, ImportError):
            raise ImportError(e.exception)
        elif isinstance(e.exception, common.MissingDependencyException):
            logger.critical('missing dependency "%s"', e.exception.dependency)
            return 255

        if isinstance(e.exception, common.EmptyError):
            logger.debug("EmptyError: %s", e.exception)
            logger.critical('could not create encoded file')
            return 255

        # in python3 we can instead do `raise e.exception` as that would show
        # the exception's original context
        logger.critical(e.exceptionMessage)
        return 255
    return ret if ret else 0
Example #25
0
 def __init__(self, filename, guess_files=False):
     self.mainfile = os.path.abspath(filename)
     self.needed_files = [self.mainfile]
     self.mods = {}
     self.unknown_mods = []
     self.guessed_mods = {}
     self.suggested_mods = {}
     self.list_installed()
     self.std_path = sysconfig.get_python_lib(standard_lib=True, prefix=os.path.realpath(sys.prefix))
     self.std_path2 = sysconfig.get_python_lib(standard_lib=True)
     self.third_path = sysconfig.get_python_lib(standard_lib=False)
     self.guess_files = guess_files
     self.cal_deps(self.mainfile)
Example #26
0
 def _site_libs(cls):
   try:
     from site import getsitepackages
     site_libs = set(getsitepackages())
   except ImportError:
     site_libs = set()
   site_libs.update([sysconfig.get_python_lib(plat_specific=False),
                     sysconfig.get_python_lib(plat_specific=True)])
   # On windows getsitepackages() returns the python stdlib too.
   if sys.prefix in site_libs:
     site_libs.remove(sys.prefix)
   real_site_libs = set(os.path.realpath(path) for path in site_libs)
   return site_libs | real_site_libs
Example #27
0
def copy_system_selinux(force=True):
    try:
        print("Try import...")
        import selinux
    except ImportError as e:
        new_error = type(e)(e.message + ". Check that 'libselinux-python' is "
                                        "installed")
        import sys
        import shutil
        from distutils import sysconfig

        if hasattr(sys, 'real_prefix'):
            # check for venv
            VENV_SITE = sysconfig.get_python_lib()
            SELINUX_PATH = os.path.join(
                sysconfig.get_python_lib(plat_specific=True,
                                         prefix=sys.real_prefix),
                "selinux")
            dest = os.path.join(VENV_SITE, "selinux")
            if force:
                shutil.rmtree(dest, ignore_errors=True)
            elif os.path.exists(dest):
                raise new_error

            # filter precompiled files
            files = [os.path.join(SELINUX_PATH, f)
                     for f in os.listdir(SELINUX_PATH)
                     if not os.path.splitext(f)[1] in (".pyc", ".pyo")]

            # add extra file for (libselinux-python-2.5-9.fc24.x86_64)
            _selinux_file = os.path.join(
                sysconfig.get_python_lib(plat_specific=True,
                                         prefix=sys.real_prefix),
                "_selinux.so")
            if os.path.exists(_selinux_file):
                files.append(_selinux_file)

            os.makedirs(dest)
            for f in files:
                shutil.copy(f, dest)

            # add extra file for (libselinux-python-2.5-13.fc25.x86_64)
            _selinux_file = os.path.join(
                sysconfig.get_python_lib(plat_specific=True,
                                         prefix=sys.real_prefix),
                "_selinux.so")
            if os.path.exists(_selinux_file):
                shutil.copy(_selinux_file, os.path.dirname(dest))
        else:
            raise new_error
        import selinux  # noqa
Example #28
0
def uninstall():
    if is_system_wide_install():
        prefix = None
    else:
        prefix = "/usr/local"
    
    for f in "iodef.py", "iodef.pyc", "_iodef.so":
        file = get_root() + "/" + get_python_lib(prefix=prefix) + "/" + f
        exists(file) and os.remove(file)

        file = get_root() + "/" + get_python_lib(plat_specific=True, prefix=prefix) + "/" + f
        exists(file) and os.remove(file)

    sys.exit(0)
Example #29
0
def data_files():
    '''Build list of data files to be installed'''
    files = []
    if os.name == 'nt':
        files.append(('.', [join('bin', 'unifield-version.txt')]))
        os.chdir('bin')
        for (dp, dn, names) in os.walk('addons'):
            files.append((dp, map(lambda x: join('bin', dp, x), names)))
        os.chdir('..')
        #for root, _, names in os.walk(join('bin','addons')):
        #    files.append((root, [join(root, name) for name in names]))
        for root, _, names in os.walk('doc'):
            files.append((root, [join(root, name) for name in names]))
        #for root, _, names in os.walk('pixmaps'):
        #    files.append((root, [join(root, name) for name in names]))
        files.append(('.', [join('bin', 'import_xml.rng'),]))
        files.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*')))
        files.append((join('service','Microsoft.VC90.CRT'), glob.glob('C:\Microsoft.VC90.CRT\*.*')))
        files.extend(fixup_data_pytz_zoneinfo())
    else:
        man_directory = join('share', 'man')
        files.append((join(man_directory, 'man1'), ['man/openerp-server.1']))
        files.append((join(man_directory, 'man5'), ['man/openerp_serverrc.5']))

        doc_directory = join('share', 'doc', 'openerp-server-%s' % version)
        files.append((doc_directory, filter(isfile, glob.glob('doc/*'))))
        files.append((join(doc_directory, 'migrate', '3.3.0-3.4.0'),
                      filter(isfile, glob.glob('doc/migrate/3.3.0-3.4.0/*'))))
        files.append((join(doc_directory, 'migrate', '3.4.0-4.0.0'),
                      filter(isfile, glob.glob('doc/migrate/3.4.0-4.0.0/*'))))

        openerp_site_packages = join(get_python_lib(prefix=''), 'openerp-server')

        files.append((openerp_site_packages, [join('bin', 'import_xml.rng'),]))

        if sys.version_info[0:2] == (2,5):
            files.append((openerp_site_packages, [ join('python25-compat','BaseHTTPServer.py'),
                                                   join('python25-compat','SimpleXMLRPCServer.py'),
                                                   join('python25-compat','SocketServer.py')]))

        for addonname, add_path in find_addons():
            addon_path = join(get_python_lib(prefix=''), 'openerp-server','addons', addonname)
            for root, dirs, innerfiles in os.walk(add_path):
                innerfiles = filter(lambda fil: os.path.splitext(fil)[1] not in ('.pyc', '.pyd', '.pyo'), innerfiles)
                if innerfiles:
                    res = os.path.normpath(join(addon_path, root.replace(join(add_path), '.')))
                    files.extend(((res, map(lambda fil: join(root, fil),
                                            innerfiles)),))

    return files
Example #30
0
def setup_python_updates():
    """Setup updates to Anaconda Python files."""
    from distutils.sysconfig import get_python_lib
    import gi.overrides

    if "ANACONDA_WIDGETS_OVERRIDES" in os.environ:
        for p in os.environ["ANACONDA_WIDGETS_OVERRIDES"].split(":"):
            gi.overrides.__path__.insert(0, os.path.abspath(p))

    # Temporary hack for F18 alpha to symlink updates and product directories
    # into tmpfs.  To be removed after beta in order to directly use content
    # from /run/install/ -- JLK
    for dirname in ("updates", "product"):
        if os.path.exists("/run/install/%s" % dirname):
            if os.path.islink("/tmp/%s" % dirname):
                # Assume updates have already been setup
                return
            os.symlink("/run/install/%s" % dirname,
                       "/tmp/%s" % dirname)

    if not os.path.exists("/tmp/updates"):
        return

    for pkg in os.listdir("/tmp/updates"):
        d = "/tmp/updates/%s" % pkg

        if not os.path.isdir(d):
            continue

        # See if the package exists in /usr/lib{64,}/python/?.?/site-packages.
        # If it does, we can set it up as an update.  If not, the pkg is
        # likely a completely new directory and should not be looked at.
        dest = "%s/%s" % (get_python_lib(), pkg)
        if not os.access(dest, os.R_OK):
            dest = "%s/%s" % (get_python_lib(1), pkg)
            if not os.access(dest, os.R_OK):
                continue
        # Symlink over everything that's in the python libdir but not in
        # the updates directory.
        symlink_updates(dest, d)

    gi.overrides.__path__.insert(0, "/run/install/updates")

    import glob
    import shutil
    for rule in glob.glob("/tmp/updates/*.rules"):
        target = "/etc/udev/rules.d/" + rule.split('/')[-1]
        shutil.copyfile(rule, target)
Example #31
0
def build_project(args):
    """
    Build a dev version of the project.

    Returns
    -------
    site_dir
        site-packages directory where it was installed

    """

    import distutils.sysconfig

    root_ok = [
        os.path.exists(os.path.join(ROOT_DIR, fn)) for fn in PROJECT_ROOT_FILES
    ]
    if not all(root_ok):
        print("To build the project, run runtests.py in "
              "git checkout or unpacked source")
        sys.exit(1)

    dst_dir = os.path.join(ROOT_DIR, 'build', 'testenv')

    env = dict(os.environ)
    cmd = [sys.executable, 'setup.py']

    # Always use ccache, if installed
    env['PATH'] = os.pathsep.join(EXTRA_PATH +
                                  env.get('PATH', '').split(os.pathsep))
    cvars = distutils.sysconfig.get_config_vars()
    compiler = env.get('CC') or cvars.get('CC', '')
    if 'gcc' in compiler:
        # Check that this isn't clang masquerading as gcc.
        if sys.platform != 'darwin' or 'gnu-gcc' in compiler:
            # add flags used as werrors
            warnings_as_errors = ' '.join([
                # from tools/travis-test.sh
                '-Werror=vla',
                '-Werror=nonnull',
                '-Werror=pointer-arith',
                '-Wlogical-op',
                # from sysconfig
                '-Werror=unused-function',
            ])
            env['CFLAGS'] = warnings_as_errors + ' ' + env.get('CFLAGS', '')
    if args.debug or args.gcov:
        # assume everyone uses gcc/gfortran
        env['OPT'] = '-O0 -ggdb'
        env['FOPT'] = '-O0 -ggdb'
        if args.gcov:
            env['OPT'] = '-O0 -ggdb'
            env['FOPT'] = '-O0 -ggdb'
            env['CC'] = cvars['CC'] + ' --coverage'
            env['CXX'] = cvars['CXX'] + ' --coverage'
            env['F77'] = 'gfortran --coverage '
            env['F90'] = 'gfortran --coverage '
            env['LDSHARED'] = cvars['LDSHARED'] + ' --coverage'
            env['LDFLAGS'] = " ".join(
                cvars['LDSHARED'].split()[1:]) + ' --coverage'

    cmd += ["build"]
    if args.parallel > 1:
        cmd += ["-j", str(args.parallel)]
    if args.debug_configure:
        cmd += ["build_src", "--verbose"]
    if args.warn_error:
        cmd += ["--warn-error"]
    # Install; avoid producing eggs so numpy can be imported from dst_dir.
    cmd += [
        'install', '--prefix=' + dst_dir,
        '--single-version-externally-managed',
        '--record=' + dst_dir + 'tmp_install_log.txt'
    ]

    from distutils.sysconfig import get_python_lib
    site_dir = get_python_lib(prefix=dst_dir, plat_specific=True)
    site_dir_noarch = get_python_lib(prefix=dst_dir, plat_specific=False)
    # easy_install won't install to a path that Python by default cannot see
    # and isn't on the PYTHONPATH.  Plus, it has to exist.
    if not os.path.exists(site_dir):
        os.makedirs(site_dir)
    if not os.path.exists(site_dir_noarch):
        os.makedirs(site_dir_noarch)
    env['PYTHONPATH'] = site_dir + ':' + site_dir_noarch

    log_filename = os.path.join(ROOT_DIR, 'build.log')

    if args.show_build_log:
        ret = subprocess.call(cmd, env=env, cwd=ROOT_DIR)
    else:
        log_filename = os.path.join(ROOT_DIR, 'build.log')
        print("Building, see build.log...")
        with open(log_filename, 'w') as log:
            p = subprocess.Popen(cmd,
                                 env=env,
                                 stdout=log,
                                 stderr=log,
                                 cwd=ROOT_DIR)
        try:
            # Wait for it to finish, and print something to indicate the
            # process is alive, but only if the log file has grown (to
            # allow continuous integration environments kill a hanging
            # process accurately if it produces no output)
            last_blip = time.time()
            last_log_size = os.stat(log_filename).st_size
            while p.poll() is None:
                time.sleep(0.5)
                if time.time() - last_blip > 60:
                    log_size = os.stat(log_filename).st_size
                    if log_size > last_log_size:
                        print("    ... build in progress")
                        last_blip = time.time()
                        last_log_size = log_size

            ret = p.wait()
        except:
            p.kill()
            p.wait()
            raise

    if ret == 0:
        print("Build OK")
    else:
        if not args.show_build_log:
            with open(log_filename, 'r') as f:
                print(f.read())
            print("Build failed!")
        sys.exit(1)

    return site_dir, site_dir_noarch
Example #32
0
    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:
            f77 = _shell_utils.NativeParser.split(f77)
            f77flags = self.flag_vars.f77
        if f90:
            f90 = _shell_utils.NativeParser.split(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
        # NOTE: this and similar examples are probably just
        # excluding --coverage flag when F90 = gfortran --coverage
        # instead of putting that flag somewhere more appropriate
        # this and similar examples where a Fortran compiler
        # environment variable has been customized by CI or a user
        # should perhaps eventually be more thoroughly tested and more
        # robustly handled
        if fix:
            fix = _shell_utils.NativeParser.split(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())
Example #33
0
    $ python -m pip install --upgrade pip setuptools
    $ python -m pip install django
This will install the latest version of Django which works on your
version of Python. If you can't upgrade your pip (or Python), request
an older version of Django:
    $ python -m pip install "django<2"
""".format(*(REQUIRED_PYTHON + CURRENT_PYTHON)))
    sys.exit(1)


# Warn if we are installing over top of an existing installation. This can
# cause issues where files that were deleted from a more recent Django are
# still present in site-packages. See #18115.
overlay_warning = False
if "install" in sys.argv:
    lib_paths = [get_python_lib()]
    if lib_paths[0].startswith("/usr/lib/"):
        # We have to try also with an explicit prefix of /usr/local in order to
        # catch Debian's custom user site-packages directory.
        lib_paths.append(get_python_lib(prefix="/usr/local"))
    for lib_path in lib_paths:
        existing_path = os.path.abspath(os.path.join(lib_path, "Fall"))
        if os.path.exists(existing_path):
            # We note the need for the warning here, but present it after the
            # command is run, so it's more likely to be seen.
            overlay_warning = True
            break


setup()
Example #34
0
 def _get_purelib():
     return get_python_lib(False)
Example #35
0
import distutils.sysconfig as sysconfig
import os
std_lib = sysconfig.get_python_lib(standard_lib=True)
for top, dirs, files in os.walk(std_lib):
    for nm in sorted(files):
        if nm != '__init__.py' and nm[-3:] == '.py':
            print(
                os.path.join(top, nm)[len(std_lib) + 1:-3].replace('\\', '.'))
Example #36
0
# populate search directories and lists of allowed file extensions
# depending on the platform we're running on.
if os.name == 'posix':
    additional_dirs.append('./')
    additional_dirs.append('/usr/lib/')
    additional_dirs.append('/usr/lib/x86_64-linux-gnu/')
    additional_dirs.append('/usr/local/lib/')

    if 'LD_LIBRARY_PATH' in os.environ:
        additional_dirs.extend(
            [item for item in os.environ['LD_LIBRARY_PATH'].split(':') if item])

    # check if running from anaconda.
    if "conda" or "continuum" in sys.version.lower():
        cur_path = get_python_lib()
        pattern = re.compile('.*\/lib\/')
        conda_lib = pattern.match(cur_path).group()
        logger.info("Adding Anaconda lib path:" + conda_lib)
        additional_dirs.append(conda_lib)

    # note - this won't catch libassimp.so.N.n, but
    # currently there's always a symlink called
    # libassimp.so in /usr/local/lib.
    ext_whitelist.append('.so')
    # libassimp.dylib in /usr/local/lib
    ext_whitelist.append('.dylib')

elif os.name == 'nt':
    ext_whitelist.append('.dll')
    path_dirs = os.environ['PATH'].split(';')
Example #37
0

def pg_version():
    """Return the PostgreSQL version as a tuple of integers."""
    match = re.search(r'(\d+)\.(\d+)', pg_config('version'))
    if match:
        return tuple(map(int, match.groups()))
    return (9, 0)


pg_version = pg_version()
libraries = ['pq']
# Make sure that the Python header files are searched before
# those of PostgreSQL, because PostgreSQL can have its own Python.h
include_dirs = [get_python_inc(), pg_config('includedir')]
library_dirs = [get_python_lib(), pg_config('libdir')]
define_macros = [('PYGRESQL_VERSION', version)]
undef_macros = []
extra_compile_args = ['-O2', '-funsigned-char']


class build_pg_ext(build_ext):
    """Customized build_ext command for PyGreSQL."""

    description = "build the PyGreSQL C extension"

    user_options = build_ext.user_options + [
        ('direct-access', None, "enable direct access functions"),
        ('large-objects', None, "enable large object support"),
        ('default-vars', None, "enable default variables use"),
        ('escaping-funcs', None, "enable string escaping functions")
Example #38
0
# FindSIP.py
#
# Copyright (c) 2007, Simon Edwards <*****@*****.**>
# Redistribution and use is allowed according to the terms of the BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.

try:
    import sipbuild
except ImportError:  # Code for SIP v4
    import sipconfig

    sipcfg = sipconfig.Configuration()
    print("sip_version:%06.0x" % sipcfg.sip_version)
    print("sip_version_str:%s" % sipcfg.sip_version_str)
    print("sip_bin:%s" % sipcfg.sip_bin)
    print("default_sip_dir:%s" % sipcfg.default_sip_dir)
    print("sip_inc_dir:%s" % sipcfg.sip_inc_dir)
else:  # Code for SIP v5
    print("sip_version:%06.0x" % sipbuild.version.SIP_VERSION)
    print("sip_version_str:%s" % sipbuild.version.SIP_VERSION_STR)

    import shutil
    print("sip_bin:%s" % shutil.which("sip5"))

    from distutils.sysconfig import get_python_lib
    python_modules_dir = get_python_lib(plat_specific=1)
    print("default_sip_dir:%s" % python_modules_dir)
Example #39
0

#
# Main section
#

info("")
info("Building PySlurm (%s)" % __version__)
info("------------------------------")
info("")

if sys.version_info[:2] < (2, 6):
    fatal("PySlurm %s requires Python version 2.6 or later (%d.%d detected)." %
          (__version__, sys.version_info[:2]))

compiler_dir = os.path.join(get_python_lib(prefix=''), 'src/pyslurm/')

CyVersion_min = "0.21"
try:
    from Cython.Distutils import build_ext
    from Cython.Compiler.Version import version as CyVersion

    info("Cython version %s installed\n" % CyVersion)

    if CyVersion < CyVersion_min:
        fatal("Please use Cython version >= %s" % CyVersion_min)
except:
    fatal("Cython (www.cython.org) is required to build PySlurm")
    fatal("Please use Cython version >= %s" % CyVersion_min)

#
Example #40
0
from __future__ import print_function
from ctypes import *
from distutils.sysconfig import get_python_lib
from os import path

try:
    d = path.dirname(__file__)
    lib = cdll.LoadLibrary("%s/libpyZipHMM.so" % (d))
    library_location = "%s/libpyZipHMM.so" % (d)
except OSError:
    python_lib = get_python_lib()
    lib = cdll.LoadLibrary(python_lib + "/libpyZipHMM.so")
    library_location = python_lib + "/libpyZipHMM.so"
except OSError as e:
    print("Error: pyZipHMM not found:")
    print("\t libpyZipHMM.so missing")
    print("Looked at:", python_lib, '/libpyZipHMM.so and ./libpyZipHMM.so')
    print("{0}: {1}".format(e.errno, e.strerror))
    exit(-1)


## HMM IO
def readHMMspec(filename):
    nStates = c_uint()
    nObservables = c_uint()

    lib.c_read_HMM_spec(
        byref(nStates), byref(nObservables),
        c_char_p(filename.encode('utf-8') if six.PY3 else filename))
    return (nStates, nObservables)
Example #41
0
def sitepackagesdir(envdir):
    from distutils.sysconfig import get_python_lib
    return dict(dir=get_python_lib(prefix=envdir))
Example #42
0
Operating System :: Microsoft :: Windows
Operating System :: POSIX
Operating System :: MacOS
Topic :: Office/Business
"""

if len(sys.argv) < 2:
    print "Syntax: setup.py command [options]"
    sys.exit(2)

command = sys.argv[1]

# create startup script
if os.name != 'nt':
    start_script = "cd %s/Planta\nexec %s ./planta.py $@\n" % (
        get_python_lib(), sys.executable)
    # write script
    f = open('planta.sh', 'w')
    f.write(start_script)
    f.close()

    script_files = ['planta.sh']

else:
    script_files = []

packages = [
    'NanScan',
    'NanScan.Generics',
    'NanScan.Backends',
    'Planta',
Example #43
0
            "The folder you are executing pip from can no longer be found.")

# under macOS + virtualenv sys.prefix is not properly resolved
# it is something like /path/to/python/bin/..
# Note: using realpath due to tmp dirs on OSX being symlinks
src_prefix = os.path.abspath(src_prefix)

# FIXME doesn't account for venv linked to global site-packages

site_packages = sysconfig.get_path("purelib")  # type: Optional[str]

# This is because of a bug in PyPy's sysconfig module, see
# https://bitbucket.org/pypy/pypy/issues/2506/sysconfig-returns-incorrect-paths
# for more information.
if platform.python_implementation().lower() == "pypy":
    site_packages = distutils_sysconfig.get_python_lib()
try:
    # Use getusersitepackages if this is present, as it ensures that the
    # value is initialised properly.
    user_site = site.getusersitepackages()
except AttributeError:
    user_site = site.USER_SITE
user_dir = expanduser('~')
if WINDOWS:
    bin_py = os.path.join(sys.prefix, 'Scripts')
    bin_user = os.path.join(user_site, 'Scripts')
    # buildout uses 'bin' on Windows too?
    if not os.path.exists(bin_py):
        bin_py = os.path.join(sys.prefix, 'bin')
        bin_user = os.path.join(user_site, 'bin')
Example #44
0
    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())
Example #45
0
except ImportError:
    cmdclass = {}

from translate import __doc__, __version__


# Alias copied from six
if sys.version_info[0] == 2:
    string_types = basestring,
else:
    string_types = str,

PRETTY_NAME = 'Translate Toolkit'
translateversion = __version__.sver

packagesdir = get_python_lib()
sitepackages = packagesdir.replace(sys.prefix + os.sep, '')

infofiles = [(join(sitepackages, 'translate'),
             [filename for filename in ('COPYING', 'README.rst')])]
initfiles = [(join(sitepackages, 'translate'), [join('translate', '__init__.py')])]

subpackages = [
        "convert",
        "filters",
        "lang",
        "misc",
        join("misc", "wsgiserver"),
        "storage",
        join("storage", "placeables"),
        join("storage", "versioncontrol"),
Example #46
0
 summary=
 'DeviceHive - the framework for interfacing applications and devices with the web cloud',
 license='MIT',
 description=
 'A framework for interfacing applications and devices with the web cloud',
 long_description=open('README.md').read(),
 keywords="web cloud api embedded tutorial",
 packages=[
     'devicehive', 'devicehive.client', 'devicehive.device',
     'devicehive.gateway'
 ],
 install_requires=['twisted', 'pyOpenSSL', 'service-identity'],
 requires=[
     'twisted (>=12.0)', 'pyOpenSSL (>=0.14)', 'service-identity (>=14.0.0)'
 ],
 data_files=[(path.join(get_python_lib(), 'devicehive'), ['LICENSE']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_binary.py']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_command.py']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_dhjson.py']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_proto.py']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_utils.py']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_wsdev.py']),
             (path.join(get_python_lib(), 'devicehive',
                        'tests'), ['tests/test_wsparser.py']),
             (path.join(get_python_lib(), 'devicehive',
Example #47
0
# Notes about STD_LIB_DIR
# Consider arch-specific installation for STD_LIB_DIR definition
# :mod:`distutils.sysconfig` contains to much hardcoded values to rely on
#
# :see: `Problems with /usr/lib64 builds <http://bugs.python.org/issue1294959>`_
# :see: `FHS <http://www.pathname.com/fhs/pub/fhs-2.3.html#LIBLTQUALGTALTERNATEFORMATESSENTIAL>`_
if sys.platform.startswith('win'):
    PY_SOURCE_EXTS = ('py', 'pyw')
    PY_COMPILED_EXTS = ('dll', 'pyd')
else:
    PY_SOURCE_EXTS = ('py', )
    PY_COMPILED_EXTS = ('so', )

try:
    STD_LIB_DIR = get_python_lib(standard_lib=1)
# get_python_lib(standard_lib=1) is not available on pypy, set STD_LIB_DIR to
# non-valid path, see https://bugs.pypy.org/issue1164
except DistutilsPlatformError:
    STD_LIB_DIR = '//'

EXT_LIB_DIR = get_python_lib()

BUILTIN_MODULES = dict(
    zip(sys.builtin_module_names, [1] * len(sys.builtin_module_names)))


class NoSourceFile(Exception):
    """exception raised when we are not able to get a python
    source file for a precompiled file
    """
Example #48
0
"""
WSGI config for homeapps project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""

import os
import sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "homeapps.settings")

from distutils.sysconfig import get_python_lib
os.environ['PYTHON_EGG_CACHE'] = get_python_lib()

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Example #49
0
to the same location where the modules of phcpy are installed.
This is accomplished via the data_files entry in the setup below.
For the installation of the GPU accelerated path trackers in double,
double double and quad double precision, instead of phcpy2c2.so,
the shared objects that are needed are phcpy2cpath_d.so (double),
phcpy2cpath_dd.so (double double), and phcpy2cpath_qd.so (quad double).
"""

from distutils.core import setup
from distutils.sysconfig import get_python_lib

setup(
    name = 'PHCpy' ,
    author = 'Jan Verschelde' ,
    author_email = '*****@*****.**' ,
    description = 'a package for Polynomial Homotopy Continuation' ,
    url = 'https://github.com/janverschelde/PHCpack' ,
    version = '0.7.7' ,
    packages = ['phcpy'] ,
    py_modules = ['phcpy/interface', 'phcpy/solver', 'phcpy/solutions', \
        'phcpy/trackers', 'phcpy/sweepers', 'phcpy/tuning', \
        'phcpy/sets', 'phcpy/cascades', 'phcpy/factor', 'phcpy/diagonal', \
        'phcpy/polytopes', 'phcpy/tropisms', 'phcpy/maps', 'phcpy/series', \
        'phcpy/schubert', 'phcpy/examples', 'phcpy/families', \
        'phcpy/dashboard', 'phcpy/server' ] ,
    license = 'GNU GENERAL PUBLIC LICENSE version 3' ,
    data_files = [(get_python_lib()+'/phcpy', ['phcpy/phcpy2c2.so'])] ,
    platforms = ['linux2'] ,
    long_description=open('README.txt').read()
)
def availableClasses(showHidden=0):
    global allClasses
    global allClasses_hidden

    def _ordering(first, second):
        ((name1, _), priority1) = first
        ((name2, _), priority2) = second

        if priority1 < priority2:
            return -1
        elif priority1 > priority2:
            return 1

        if name1 < name2:
            return -1
        elif name1 > name2:
            return 1

        return 0

    if not showHidden:
        if allClasses:
            return allClasses
    else:
        if allClasses_hidden:
            return allClasses_hidden

    path = []

    env_path = []
    if "ANACONDA_INSTALL_CLASSES" in os.environ:
        env_path += os.environ["ANACONDA_INSTALL_CLASSES"].split(":")

    for d in env_path + [
            "installclasses", "/tmp/updates/pyanaconda/installclasses",
            "/tmp/product/pyanaconda/installclasses",
            "%s/pyanaconda/installclasses" % get_python_lib(plat_specific=1)
    ]:
        if os.access(d, os.R_OK):
            path.append(d)

    # append the location of installclasses to the python path so we
    # can import them
    sys.path = path + sys.path

    files = []
    for p in reversed(path):
        files += os.listdir(p)

    done = {}
    lst = []
    for fileName in files:
        if fileName[0] == '.':
            continue
        if len(fileName) < 4:
            continue
        if fileName[-3:] != ".py" and fileName[-4:-1] != ".py":
            continue
        mainName = fileName.split(".")[0]
        if done.has_key(mainName):
            continue
        done[mainName] = 1

        try:
            found = imputil.imp.find_module(mainName)
        except ImportError:
            log.warning("module import of %s failed: %s", mainName,
                        sys.exc_type)
            continue

        try:
            loaded = imputil.imp.load_module(mainName, found[0], found[1],
                                             found[2])

            obj = loaded.InstallClass

            if obj.__dict__.has_key('sortPriority'):
                sortOrder = obj.sortPriority
            else:
                sortOrder = 0

            if obj.hidden == 0 or showHidden == 1:
                lst.append(((obj.name, obj), sortOrder))
        except (ImportError, AttributeError):
            log.warning("module import of %s failed: %s", mainName,
                        sys.exc_type)

    lst.sort(_ordering)
    for (item, _) in lst:
        if showHidden:
            allClasses_hidden += [item]
        else:
            allClasses += [item]

    if showHidden:
        return allClasses_hidden
    else:
        return allClasses
Example #51
0
    def write(self, s):
        self.fp.write(s)

    def writelines(self, lines):
        self.fp.writelines(lines)

    def flush(self):
        self.fp.flush()


stdout_redirector = OutputRedirector(sys.stdout)
stderr_redirector = OutputRedirector(sys.stderr)

SYSSTR = platform.system()
SITE_PAKAGE_PATH = get_python_lib()

FIELDS = {
    "testPass": 0,
    "testResult": [],
    "testName": "",
    "testAll": 0,
    "testFail": 0,
    "beginTime": "",
    "totalTime": "",
    "testSkip": 0
}


class PATH:
    """ all file PATH meta """
Example #52
0
		"libuna",
		"libcfile",
		"libcpath",
		"libbfio",
		"libewf",
	],
	library_dirs = [
		"..\\msvscpp\\Release",
	],
)

# TODO: what about license, description and platform in egg file
setup(
	name = "pyewf",
	url = "http://code.google.com/p/libewf/",
	version = "20130416",
	description = "Python bindings module for libewf",
	author = "Joachim Metz",
	author_email = "*****@*****.**",
	ext_modules = [
		module,
	],
	data_files = [
		(sysconfig.get_python_lib(), [
			"..\\msvscpp\\Release\\libewf.dll",
			"..\\msvscpp\\Release\\zlib.dll",
		]),
	],
)

Example #53
0
#!/usr/bin/env python

import os, os.path
import sys
import distutils.sysconfig as sysconfig

# use this to install a shortcut on the desktop of the installer only
#desktop = get_special_folder_path("CSIDL_DESKTOPDIRECTORY")

# use this to install a shortcut on the desktop of all users
desktop = get_special_folder_path("CSIDL_COMMON_DESKTOPDIRECTORY")

shortcut = os.path.join(desktop, 'Pythics.lnk')
examples = os.path.join(sysconfig.get_python_lib(True), 'pythics', 'start.py')

if sys.argv[1] == '-install':
    create_shortcut(examples, 'Start Pythics', shortcut)
    print 'Created Pythics shortcut on desktop.'
elif os.path.exists(shortcut):
    os.remove(shortcut)
Example #54
0
from distutils.sysconfig import get_python_lib
import logging
import configparser
import time

logging.basicConfig(filename="/var/log/patching/patching_auto_email.log",
                    filemode="a",
                    format="%(asctime)s %(message)s",
                    datefmt="%d/%m/%Y %H:%M:%S",
                    level=logging.INFO)
logging.info(
    "==================================================================")
logging.info("Starting the script...")

os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(get_python_lib())


def get_settings():
    '''parse the config file'''
    parse_conf = configparser.ConfigParser()
    parse_conf.read("./settings.cfg")
    return parse_conf['auto_e_mail_notifications']


def extract_needed_servers():
    '''function for read csv files and extract servers which should be patched between now+13 min. and now+28 min.'''
    logging.info("Searching needed servers from csv-files...")
    servers_for_sending_email = {}
    csv_files = glob.glob('./*linux_*.csv')
    logging.info(
Example #55
0
from distutils.sysconfig import get_python_lib
from setuptools import setup, Extension, find_packages
from os import path

README_md = path.join(path.abspath(path.dirname(__file__)), 'README.md')

with open(README_md, 'r') as f:
    long_description = f.read()

vrpc_path = path.join(get_python_lib(), 'vrpc')
vrpc_module_cpp = path.join(vrpc_path, 'module.cpp')

module = Extension('vrpc_example_ext',
                   include_dirs=[vrpc_path, './cpp'],
                   define_macros=[('VRPC_COMPILE_AS_ADDON', '<binding.cpp>'),
                                  ('VRPC_MODULE_NAME', '"vrpc_example_ext"'),
                                  ('VRPC_MODULE_FUNC',
                                   'PyInit_vrpc_example_ext')],
                   extra_compile_args=['-std=c++14', '-fPIC'],
                   sources=[vrpc_module_cpp, './cpp/Bar.cpp'],
                   language='c++')

setup(name='vrpc-python-example',
      version='1.0.0',
      license='MIT',
      description='Example project demonstrating the usage of vrpc',
      long_description=long_description,
      long_description_content_type='text/markdown',
      author='Burkhard C. Heisen',
      author_email='*****@*****.**',
      packages=find_packages(),
Example #56
0
"""

warnings.simplefilter("ignore", UserWarning)

if sys.platform == "darwin":
    LIBNAME = "libxnd.dylib"
    LIBSONAME = "libxnd.0.dylib"
    LIBSHARED = "libxnd.0.2.0dev3.dylib"
else:
    LIBNAME = "libxnd.so"
    LIBSONAME = "libxnd.so.0"
    LIBSHARED = "libxnd.so.0.2.0dev3"
    LIBNDTYPES = "libndtypes.so.0.2.0dev3"

if "install" in sys.argv or "bdist_wheel" in sys.argv:
    CONFIGURE_INCLUDES = "%s/ndtypes" % get_python_lib()
    CONFIGURE_LIBS = CONFIGURE_INCLUDES
    INCLUDES = LIBS = [CONFIGURE_INCLUDES]
    LIBXNDDIR = "%s/xnd" % get_python_lib()
    INSTALL_LIBS = True
elif "conda_install" in sys.argv:
    site = "%s/ndtypes" % get_python_lib()
    sys_includes = os.path.join(os.environ['PREFIX'], "include")
    libdir = "Library/bin" if sys.platform == "win32" else "lib"
    sys_libs = os.path.join(os.environ['PREFIX'], libdir)
    CONFIGURE_INCLUDES = INCLUDES = [sys_includes, site]
    LIBS = [sys_libs, site]
    LIBXNDDIR = "%s/xnd" % get_python_lib()
    INSTALL_LIBS = False
else:
    CONFIGURE_INCLUDES = "../python/ndtypes"
Example #57
0
# Create the setdir.sh and setdir.csh scripts; they will be recreated
# each time setup.py is run, but it does not matter.

scripttempdir = 'build/temp.' + get_platform(
) + '-%s.%s' % sys.version_info[0:2]
mkpath(scripttempdir)

setdir_sh = open(scripttempdir + '/synthlisa-setdir.sh', 'w')
setdir_csh = open(scripttempdir + '/synthlisa-setdir.csh', 'w')
recompile_sh = open(scripttempdir + '/synthlisa-recompile.sh', 'w')

pythonpath = ''
installpath = sys.exec_prefix

if synthlisa_prefix:
    pythonpath = get_python_lib(prefix=synthlisa_prefix)
    installpath = synthlisa_prefix

# not needed with numpy, which can find the module from site-packages

# if numpy_prefix:
#     if pythonpath:
#         pythonpath = pythonpath + ':'
#
#     pythonpath = pythonpath + get_python_lib(prefix=numpy_prefix) + '/numpy'

mpi_prefix = numpy_prefix

if mpi_prefix:
    if pythonpath:
        pythonpath = pythonpath + ':'
Example #58
0
def main(_args=None):
    """ Command-line entry point """
    global args
    args = _args or parser.parse_args()

    # If warnings not externally managed, show deprecation warnings
    if not sys.warnoptions:
        warnings.simplefilter("once", DeprecationWarning)

    if args.close_stdin:
        sys.stdin.close()

    if (args.html or args.http) and not args.output_dir:
        args.output_dir = 'html'

    if args.html_dir:
        _warn_deprecated('--html-dir', '--output-dir')
        args.output_dir = args.html_dir
    if args.overwrite:
        _warn_deprecated('--overwrite', '--force')
        args.force = args.overwrite

    template_config = {}
    for config_str in args.config:
        try:
            key, value = config_str.split('=', 1)
            value = ast.literal_eval(value)
            template_config[key] = value
        except Exception:
            raise ValueError(
                f'Error evaluating --config statement "{config_str}". '
                'Make sure string values are quoted?')

    if args.html_no_source:
        _warn_deprecated('--html-no-source', '-c show_source_code=False', True)
        template_config['show_source_code'] = False
    if args.link_prefix:
        _warn_deprecated('--link-prefix', '-c link_prefix="foo"', True)
        template_config['link_prefix'] = args.link_prefix
    if args.external_links:
        _warn_deprecated('--external-links')
        template_config['external_links'] = True

    if args.template_dir is not None:
        if not path.isdir(args.template_dir):
            print(
                f'Error: Template dir {args.template_dir!r} is not a directory',
                file=sys.stderr)
            sys.exit(1)
        pdoc.tpl_lookup.directories.insert(0, args.template_dir)

    # Support loading modules specified as python paths relative to cwd
    sys.path.append(os.getcwd())

    # Virtual environment handling for pdoc script run from system site
    try:
        venv_dir = os.environ['VIRTUAL_ENV']
    except KeyError:
        pass  # pdoc was not invoked while in a virtual environment
    else:
        from glob import glob
        from distutils.sysconfig import get_python_lib
        libdir = get_python_lib(prefix=venv_dir)
        sys.path.append(libdir)
        # Resolve egg-links from `setup.py develop` or `pip install -e`
        # XXX: Welcome a more canonical approach
        for pth in glob(path.join(libdir, '*.egg-link')):
            try:
                with open(pth) as f:
                    sys.path.append(path.join(libdir, f.readline().rstrip()))
            except IOError:
                warn(f'Invalid egg-link in venv: {pth!r}')

    if args.http:
        template_config['link_prefix'] = "/"

        # Run the HTTP server.
        _WebDoc.args = args  # Pass params to HTTPServer xP
        _WebDoc.template_config = template_config

        host, _, port = args.http.partition(':')
        host = host or DEFAULT_HOST
        port = int(port or DEFAULT_PORT)

        print(f'Starting pdoc server on {host}:{port}', file=sys.stderr)
        httpd = HTTPServer((host, port), _WebDoc)
        print(f"pdoc server ready at http://{host}:{port}", file=sys.stderr)

        # Allow tests to perform `pdoc.cli._httpd.shutdown()`
        global _httpd
        _httpd = httpd

        try:
            httpd.serve_forever()
        finally:
            httpd.server_close()
            sys.exit(0)

    docfilter = None
    if args.filter and args.filter.strip():

        def docfilter(obj, _filters=args.filter.strip().split(',')):
            return any(f in obj.refname
                       or isinstance(obj, pdoc.Class) and f in obj.doc
                       for f in _filters)

    modules = [
        pdoc.Module(module, docfilter=docfilter, skip_errors=args.skip_errors)
        for module in args.modules
    ]
    pdoc.link_inheritance()

    if args.pdf:
        _print_pdf(modules, **template_config)
        import textwrap
        PANDOC_CMD = textwrap.indent(_PANDOC_COMMAND, '    ')
        print(f"""
PDF-ready markdown written to standard output.
                              ^^^^^^^^^^^^^^^
Convert this file to PDF using e.g. Pandoc:

{PANDOC_CMD}

or using Python-Markdown and Chrome/Chromium/WkHtmlToPDF:

    markdown_py --extension=meta         \\
                --extension=abbr         \\
                --extension=attr_list    \\
                --extension=def_list     \\
                --extension=fenced_code  \\
                --extension=footnotes    \\
                --extension=tables       \\
                --extension=admonition   \\
                --extension=smarty       \\
                --extension=toc          \\
                pdf.md > pdf.html

    chromium --headless --disable-gpu --print-to-pdf=pdf.pdf pdf.html

    wkhtmltopdf --encoding utf8 -s A4 --print-media-type pdf.html pdf.pdf

or similar, at your own discretion.""",
              file=sys.stderr)
        sys.exit(0)

    for module in modules:
        if args.html:
            _quit_if_exists(module, ext='.html')
            recursive_write_files(module, ext='.html', **template_config)
        elif args.output_dir:  # Generate text files
            _quit_if_exists(module, ext='.md')
            recursive_write_files(module, ext='.md', **template_config)
        else:
            sys.stdout.write(module.text(**template_config))
            # Two blank lines between two modules' texts
            sys.stdout.write(os.linesep * (1 + 2 * int(module != modules[-1])))

    if args.html:
        lunr_config = pdoc._get_config(**template_config).get('lunr_search')
        if lunr_config is not None:
            _generate_lunr_search(modules,
                                  lunr_config.get("index_docstrings", True),
                                  template_config)
Example #59
0
            os.path.abspath(os.path.join(CUDF_ROOT, "../include/cudf")),
            os.path.abspath(os.path.join(CUDF_ROOT, "../include")),
            os.path.abspath(
                os.path.join(CUDF_ROOT,
                             "../libcudf_kafka/include/cudf_kafka")),
            os.path.join(CUDF_ROOT, "include"),
            os.path.join(CUDF_ROOT, "_deps/libcudacxx-src/include"),
            os.path.join(
                os.path.dirname(sysconfig.get_path("include")),
                "libcudf/libcudacxx",
            ),
            os.path.dirname(sysconfig.get_path("include")),
            np.get_include(),
            cuda_include_dir,
        ],
        library_dirs=([get_python_lib(),
                       os.path.join(os.sys.prefix, "lib")]),
        libraries=["cudf", "cudf_kafka"],
        language="c++",
        extra_compile_args=["-std=c++14"],
    )
]

setup(
    name="cudf_kafka",
    version=versioneer.get_version(),
    description="cuDF Kafka Datasource",
    url="https://github.com/rapidsai/cudf",
    author="NVIDIA Corporation",
    license="Apache 2.0",
    classifiers=[
Example #60
0
from distutils import sysconfig
import json
import logging
import os
import pprint
import struct
import sys
import time
import traceback

import usb

from stats_manager import StatsManager

# Directory where hdctools installs configuration files into.
LIB_DIR = os.path.join(sysconfig.get_python_lib(standard_lib=False), 'servo',
                       'data')

# Potential config file locations: current working directory, the same directory
# as powerlog.py file or LIB_DIR.
CONFIG_LOCATIONS = [
    os.getcwd(),
    os.path.dirname(os.path.realpath(__file__)), LIB_DIR
]


def logoutput(msg):
    print(msg)
    sys.stdout.flush()