コード例 #1
0
ファイル: dist.py プロジェクト: LANJr4D/FRED
 def _show_help (self, parser, global_options=1, display_options=1, commands=[]):
     "Join individual messages after default help"
     _Distribution._show_help(self, parser, global_options, display_options, commands)
     # display additions
     for command_class in self.cmdclass.values():
         if hasattr(command_class, 'show_after_help'):
             command_class.show_after_help(commands) # must be staticmethod
コード例 #2
0
ファイル: test_dist.py プロジェクト: 3lnc/cpython
    def test_find_config_files_disable(self):
        # Ticket #1180: Allow user to disable their home config file.
        temp_home = self.mkdtemp()
        if os.name == 'posix':
            user_filename = os.path.join(temp_home, ".pydistutils.cfg")
        else:
            user_filename = os.path.join(temp_home, "pydistutils.cfg")

        with open(user_filename, 'w') as f:
            f.write('[distutils]\n')

        def _expander(path):
            return temp_home

        old_expander = os.path.expanduser
        os.path.expanduser = _expander
        try:
            d = Distribution()
            all_files = d.find_config_files()

            d = Distribution(attrs={'script_args': ['--no-user-cfg']})
            files = d.find_config_files()
        finally:
            os.path.expanduser = old_expander

        # make sure --no-user-cfg disables the user cfg file
        self.assertEqual(len(all_files)-1, len(files))
コード例 #3
0
ファイル: pyxbuild.py プロジェクト: enyst/plexnet
def pyx_to_dll(filename, ext = None, force_rebuild = 0):
    """Compile a PYX file to a DLL and return the name of the generated .so 
       or .dll ."""
    assert os.path.exists(filename)

    path, name = os.path.split(filename)

    if not ext:
        modname, extension = os.path.splitext(name)
	assert extension == ".pyx", extension
        ext = Extension(name=modname, sources=[filename])

    if DEBUG:
        quiet = "--verbose"
    else:
	quiet = "--quiet"
    args = [quiet, "build_ext"]
    if force_rebuild:
        args.append("--force")
    dist = Distribution({"script_name": None, "script_args": args})
    if not dist.ext_modules:
        dist.ext_modules = []
    dist.ext_modules.append(ext)
    dist.cmdclass = {'build_ext': build_ext}
    build = dist.get_command_obj('build')
    build.build_base = os.path.join(path, "_pyxbld")

    try:
        ok = dist.parse_command_line()
    except DistutilsArgError, msg:
        raise
コード例 #4
0
ファイル: conftest.py プロジェクト: antoine1fr/pygirl
def compile_so_file():
    from distutils.dist import Distribution
    from distutils.extension import Extension
    from distutils.ccompiler import get_default_compiler
    udir = py.test.ensuretemp('_ctypes_test')
    cfile = py.magic.autopath().dirpath().join("_ctypes_test.c")
    saved_environ = os.environ.items()
    olddir = udir.chdir()
    try:
        attrs = {
            'name': "_ctypes_test",
            'ext_modules': [
                Extension("_ctypes_test", [str(cfile)]),
                ],
            'script_name': 'setup.py',
            'script_args': ['-q', 'build_ext', '--inplace'],
            }
        dist = Distribution(attrs)
        if not dist.parse_command_line():
            raise ValueError, "distutils cmdline parse error"
        dist.run_commands()
    finally:
        olddir.chdir()
        for key, value in saved_environ:
            if os.environ.get(key) != value:
                os.environ[key] = value

    if sys.platform == 'win32':
        so_ext = '.dll'
    else:
        so_ext = '.so'
    return udir.join('_ctypes_test' + so_ext)
コード例 #5
0
def get_dummy_distribution():
    """
    Returns a distutils Distribution object used to instrument the setup
    environment before calling the actual setup() function.
    """

    from .setup_helpers import _module_state

    if _module_state['registered_commands'] is None:
        raise RuntimeError(
            'astropy_helpers.setup_helpers.register_commands() must be '
            'called before using '
            'astropy_helpers.setup_helpers.get_dummy_distribution()')

    # Pre-parse the Distutils command-line options and config files to if
    # the option is set.
    dist = Distribution({'script_name': os.path.basename(sys.argv[0]),
                         'script_args': sys.argv[1:]})
    dist.cmdclass.update(_module_state['registered_commands'])

    with silence():
        try:
            dist.parse_config_files()
            dist.parse_command_line()
        except (DistutilsError, AttributeError, SystemExit):
            # Let distutils handle DistutilsErrors itself AttributeErrors can
            # get raise for ./setup.py --help SystemExit can be raised if a
            # display option was used, for example
            pass

    return dist
コード例 #6
0
    def runTest(self):
        import nose.commands

        from setuptools import Command
        from distutils.dist import Distribution
        from nose.config import Config, user_config_files
        from nose.plugins import PluginManager

        class DummyNose(Command):
            description = "Dummy"
            manager = PluginManager()
            manager.plugins = [RandomlyPlugin()]
            __config = Config(
                files=user_config_files(),
                plugins=manager)
            __parser = __config.getParser()
            user_options = nose.commands.get_user_options(__parser)

            def initialize_options(self):
                pass

            def finalize_options(self):
                pass

            def run(self):
                pass

        dist = Distribution({'cmdclass': {'nosetests': DummyNose}})
        dist.script_args = ['nosetests']

        # This test should merely not throw an exception
        dist.parse_command_line()
コード例 #7
0
def distutils_scheme(dist_name, user=False, home=None, root=None):
    """
    Return a distutils install scheme
    """
    from distutils.dist import Distribution

    scheme = {}
    d = Distribution({'name': dist_name})
    d.parse_config_files()
    i = d.get_command_obj('install', create=True)
    # NOTE: setting user or home has the side-effect of creating the home dir or
    # user base for installations during finalize_options()
    # ideally, we'd prefer a scheme class that has no side-effects.
    i.user = user or i.user
    i.home = home or i.home
    i.root = root or i.root
    i.finalize_options()
    for key in SCHEME_KEYS:
        scheme[key] = getattr(i, 'install_'+key)

    if running_under_virtualenv():
        scheme['headers'] = os.path.join(sys.prefix,
                                    'include',
                                    'site',
                                    'python' + sys.version[:3],
                                    dist_name)

        if root is not None:
            scheme["headers"] = os.path.join(
                root,
                os.path.abspath(scheme["headers"])[1:],
            )

    return scheme
コード例 #8
0
ファイル: base.py プロジェクト: pysmt/pysmt
def package_install_site(name='', user=False, plat_specific=False):
    """pip-inspired, distutils-based method for fetching the
    default install location (site-packages path).

    Returns virtual environment or system site-packages, unless
    `user=True` in which case returns user-site (typ. under `~/.local/
    on linux).

    If there's a distinction (on a particular system) between platform
    specific and pure python package locations, set `plat_specific=True`
    to retrieve the former.
    """

    dist = Distribution({'name': name})
    dist.parse_config_files()
    inst = dist.get_command_obj('install', create=True)
    # NOTE: specifying user=True will create user-site
    if user:
        inst.user = user
        inst.prefix = ""
    inst.finalize_options()

    # platform-specific site vs. purelib (platform-independent) site
    if plat_specific:
        loc = inst.install_platlib
    else:
        loc = inst.install_purelib

    # install_lib specified in setup.cfg has highest precedence
    if 'install_lib' in dist.get_option_dict('install'):
        loc = inst.install_lib

    return loc
コード例 #9
0
ファイル: test_dist.py プロジェクト: hycxa/kbengine
    def test_custom_pydistutils(self):
        # fixes #2166
        # make sure pydistutils.cfg is found
        if os.name == "posix":
            user_filename = ".pydistutils.cfg"
        else:
            user_filename = "pydistutils.cfg"

        temp_dir = self.mkdtemp()
        user_filename = os.path.join(temp_dir, user_filename)
        f = open(user_filename, "w")
        try:
            f.write(".")
        finally:
            f.close()

        try:
            dist = Distribution()

            # linux-style
            if sys.platform in ("linux", "darwin"):
                os.environ["HOME"] = temp_dir
                files = dist.find_config_files()
                self.assertIn(user_filename, files)

            # win32-style
            if sys.platform == "win32":
                # home drive should be found
                os.environ["HOME"] = temp_dir
                files = dist.find_config_files()
                self.assertIn(user_filename, files, "%r not found in %r" % (user_filename, files))
        finally:
            os.remove(user_filename)
コード例 #10
0
ファイル: test_dist.py プロジェクト: 3lnc/cpython
    def test_custom_pydistutils(self):
        # fixes #2166
        # make sure pydistutils.cfg is found
        if os.name == 'posix':
            user_filename = ".pydistutils.cfg"
        else:
            user_filename = "pydistutils.cfg"

        temp_dir = self.mkdtemp()
        user_filename = os.path.join(temp_dir, user_filename)
        f = open(user_filename, 'w')
        try:
            f.write('.')
        finally:
            f.close()

        try:
            dist = Distribution()

            # linux-style
            if sys.platform in ('linux', 'darwin'):
                os.environ['HOME'] = temp_dir
                files = dist.find_config_files()
                self.assertIn(user_filename, files)

            # win32-style
            if sys.platform == 'win32':
                # home drive should be found
                os.environ['HOME'] = temp_dir
                files = dist.find_config_files()
                self.assertIn(user_filename, files,
                              '%r not found in %r' % (user_filename, files))
        finally:
            os.remove(user_filename)
コード例 #11
0
ファイル: __init__.py プロジェクト: Soolo-ss/Solo2
def get_include(user=False):
    from distutils.dist import Distribution
    import os
    import sys

    # Are we running in a virtual environment?
    virtualenv = hasattr(sys, 'real_prefix') or \
        sys.prefix != getattr(sys, "base_prefix", sys.prefix)

    if virtualenv:
        return os.path.join(sys.prefix, 'include', 'site',
                            'python' + sys.version[:3])
    else:
        dist = Distribution({'name': 'pybind11'})
        dist.parse_config_files()

        dist_cobj = dist.get_command_obj('install', create=True)

        # Search for packages in user's home directory?
        if user:
            dist_cobj.user = user
            dist_cobj.prefix = ""
        dist_cobj.finalize_options()

        return os.path.dirname(dist_cobj.install_headers)
コード例 #12
0
 def __init__(self, attrs):
     self.po = None
     self.appdata = None
     self.appmodules = None
     self.links = None
     self.configurable = None
     Distribution.__init__(self, attrs)
コード例 #13
0
ファイル: frompip.py プロジェクト: rbtcollins/setuptools_shim
def distutils_scheme(dist_name, user=False, home=None, root=None,
                     isolated=False, prefix=None):
    """
    Return a distutils install scheme
    """
    from distutils.dist import Distribution

    scheme = {}

    if isolated:
        extra_dist_args = {"script_args": ["--no-user-cfg"]}
    else:
        extra_dist_args = {}
    dist_args = {'name': dist_name}
    dist_args.update(extra_dist_args)

    d = Distribution(dist_args)
    d.parse_config_files()
    i = d.get_command_obj('install', create=True)
    # NOTE: setting user or home has the side-effect of creating the home dir
    # or user base for installations during finalize_options()
    # ideally, we'd prefer a scheme class that has no side-effects.
    assert not (user and prefix), "user={0} prefix={1}".format(user, prefix)
    i.user = user or i.user
    if user:
        i.prefix = ""
    i.prefix = prefix or i.prefix
    i.home = home or i.home
    i.root = root or i.root
    i.finalize_options()
    for key in SCHEME_KEYS:
        scheme[key] = getattr(i, 'install_' + key)

    # install_lib specified in setup.cfg should install *everything*
    # into there (i.e. it takes precedence over both purelib and
    # platlib).  Note, i.install_lib is *always* set after
    # finalize_options(); we only want to override here if the user
    # has explicitly requested it hence going back to the config
    if 'install_lib' in d.get_option_dict('install'):
        scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))

    if running_under_virtualenv():
        scheme['headers'] = os.path.join(
            sys.prefix,
            'include',
            'site',
            'python' + sys.version[:3],
            dist_name,
        )

        if root is not None:
            path_no_drive = os.path.splitdrive(
                os.path.abspath(scheme["headers"]))[1]
            scheme["headers"] = os.path.join(
                root,
                path_no_drive[1:],
            )

    return scheme
コード例 #14
0
ファイル: setup.py プロジェクト: chifflier/prewikka
    def __init__(self, attrs):
        try:
            os.remove("prewikka/siteconfig.py")
        except:
            pass

        self.conf_files = [ ]
        Distribution.__init__(self, attrs)
コード例 #15
0
ファイル: test_dist.py プロジェクト: willingc/cpython
 def test_classifier(self):
     attrs = {'name': 'Boa', 'version': '3.0',
              'classifiers': ['Programming Language :: Python :: 3']}
     dist = Distribution(attrs)
     self.assertEqual(dist.get_classifiers(),
                      ['Programming Language :: Python :: 3'])
     meta = self.format_metadata(dist)
     self.assertIn('Metadata-Version: 1.1', meta)
コード例 #16
0
ファイル: test_dist.py プロジェクト: hycxa/kbengine
    def test_finalize_options(self):
        attrs = {"keywords": "one,two", "platforms": "one,two"}

        dist = Distribution(attrs=attrs)
        dist.finalize_options()

        # finalize_option splits platforms and keywords
        self.assertEqual(dist.metadata.platforms, ["one", "two"])
        self.assertEqual(dist.metadata.keywords, ["one", "two"])
コード例 #17
0
ファイル: test_dist.py プロジェクト: hycxa/kbengine
 def test_provides(self):
     attrs = {"name": "package", "version": "1.0", "provides": ["package", "package.sub"]}
     dist = Distribution(attrs)
     self.assertEqual(dist.metadata.get_provides(), ["package", "package.sub"])
     self.assertEqual(dist.get_provides(), ["package", "package.sub"])
     meta = self.format_metadata(dist)
     self.assertIn("Metadata-Version: 1.1", meta)
     self.assertNotIn("requires:", meta.lower())
     self.assertNotIn("obsoletes:", meta.lower())
コード例 #18
0
ファイル: test_dist.py プロジェクト: webiumsk/WOT-0.9.15.1
 def test_show_help(self):
     dist = Distribution()
     sys.argv = []
     dist.help = 1
     dist.script_name = 'setup.py'
     with captured_stdout() as s:
         dist.parse_command_line()
     output = [ line for line in s.getvalue().split('\n') if line.strip() != '' ]
     self.assertTrue(output)
コード例 #19
0
ファイル: dist.py プロジェクト: strohel/works
 def __init__(self, attrs):
     self.cflags = None  # Default CFLAGS overridable by setup.cfg
     self.ldflags = None  # Default LDFLAGS overridable by setup.cfg
     self.ext_options = None
     Distribution.__init__(self, attrs)
     self.cmdclass['build_py'] = build_py
     self.cmdclass['build_ext'] = build_ext
     self.cmdclass['test'] = test
     self.modules_to_cythonize = set()
コード例 #20
0
ファイル: setup.py プロジェクト: 4sp1r3/prewikka
    def __init__(self, attrs):
        try:
            os.remove("prewikka/siteconfig.py")
        except:
            pass

        self.conf_files = [ ]
        self.closed_source = os.path.exists("PKG-INFO")
        Distribution.__init__(self, attrs)
コード例 #21
0
ファイル: setup.py プロジェクト: rsms/pyca
 def __init__(self, attrs=None):
   Distribution.__init__(self, attrs)
   self.cmdclass = {
     'config': config,
     'build_ext': build_ext,
     'sdist': sdist,
     'docs': sphinx_build,
     'clean': clean,
   }
コード例 #22
0
ファイル: babel.py プロジェクト: EnTeQuAk/django-babel
    def handle_makemessages(self, **options):
        locale_paths = list(settings.LOCALE_PATHS)
        domain = options.pop('domain')
        locales = options.pop('locale')

        # support for mapping file specification via setup.cfg
        # TODO: Try to support all possible options.
        distribution = Distribution()
        distribution.parse_config_files(distribution.find_config_files())

        mapping_file = options.pop('mapping_file', None)
        has_extract = 'extract_messages' in distribution.command_options
        if mapping_file is None and has_extract:
            opts = distribution.command_options['extract_messages']
            try:
                mapping_file = opts['mapping_file'][1]
            except (IndexError, KeyError):
                mapping_file = None

        for path in locale_paths:
            potfile = os.path.join(path, '%s.pot' % domain)

            if not os.path.exists(path):
                os.makedirs(path)

            if not os.path.exists(potfile):
                with open(potfile, 'wb') as fobj:
                    fobj.write(b'')

            cmd = ['pybabel', 'extract', '-o', potfile]

            if mapping_file is not None:
                cmd.extend(['-F', mapping_file])

            cmd.append(os.path.dirname(os.path.relpath(path)))

            call(cmd)

            for locale in locales:
                pofile = os.path.join(
                    os.path.dirname(potfile),
                    locale,
                    'LC_MESSAGES',
                    '%s.po' % domain)

                if not os.path.isdir(os.path.dirname(pofile)):
                    os.makedirs(os.path.dirname(pofile))

                if not os.path.exists(pofile):
                    with open(pofile, 'wb') as fobj:
                        fobj.write(b'')

                cmd = ['pybabel', 'update', '-D', domain,
                       '-i', potfile,
                       '-d', os.path.relpath(path),
                       '-l', locale]
                call(cmd)
コード例 #23
0
ファイル: setup.py プロジェクト: C3BI-pasteur-fr/blast2seqids
 def __init__(self, attrs = None):
     #It's important to define opotions before to call __init__
     #otherwise AttributeError: UsageDistribution instance has no attribute 'conf_files'
     self.conf_files = None
     self.doc_files = None
     self.fix_prefix = None
     self.fix_conf = None
     Distribution.__init__(self, attrs = attrs)
     self.common_usage = """\
コード例 #24
0
ファイル: test_dist.py プロジェクト: hycxa/kbengine
    def test_get_command_packages(self):
        dist = Distribution()
        self.assertEqual(dist.command_packages, None)
        cmds = dist.get_command_packages()
        self.assertEqual(cmds, ["distutils.command"])
        self.assertEqual(dist.command_packages, ["distutils.command"])

        dist.command_packages = "one,two"
        cmds = dist.get_command_packages()
        self.assertEqual(cmds, ["distutils.command", "one", "two"])
コード例 #25
0
ファイル: test_dist.py プロジェクト: webiumsk/WOT-0.9.15.1
 def test_get_command_packages(self):
     dist = Distribution()
     self.assertEqual(dist.command_packages, None)
     cmds = dist.get_command_packages()
     self.assertEqual(cmds, ['distutils.command'])
     self.assertEqual(dist.command_packages, ['distutils.command'])
     dist.command_packages = 'one,two'
     cmds = dist.get_command_packages()
     self.assertEqual(cmds, ['distutils.command', 'one', 'two'])
     return
コード例 #26
0
ファイル: test_dist.py プロジェクト: 3lnc/cpython
    def test_finalize_options(self):
        attrs = {'keywords': 'one,two',
                 'platforms': 'one,two'}

        dist = Distribution(attrs=attrs)
        dist.finalize_options()

        # finalize_option splits platforms and keywords
        self.assertEqual(dist.metadata.platforms, ['one', 'two'])
        self.assertEqual(dist.metadata.keywords, ['one', 'two'])
コード例 #27
0
ファイル: test_dist.py プロジェクト: hycxa/kbengine
    def test_show_help(self):
        # smoke test, just makes sure some help is displayed
        dist = Distribution()
        sys.argv = []
        dist.help = 1
        dist.script_name = "setup.py"
        with captured_stdout() as s:
            dist.parse_command_line()

        output = [line for line in s.getvalue().split("\n") if line.strip() != ""]
        self.assertTrue(output)
コード例 #28
0
ファイル: setup.py プロジェクト: otsaloma/gaupol
 def __init__(self, attrs=None):
     if sys.platform == "win32":
         self.executables = []
     self.mandir = "share/man"
     self.with_aeidon = True
     self.with_gaupol = True
     self.with_iso_codes = True
     distribution.__init__(self, attrs)
     self.data_files = []
     self.packages = []
     self.scripts = []
コード例 #29
0
ファイル: utils.py プロジェクト: 18600597055/hue
def compiler_type():
    """
    Gets the compiler type from distutils. On Windows with MSVC it will be
    "msvc". On OS X and linux it is "unix".
    """
    dist = Distribution()
    dist.parse_config_files()
    cmd = dist.get_command_obj('build')
    cmd.ensure_finalized()
    compiler = new_compiler(compiler=cmd.compiler)
    return compiler.compiler_type
コード例 #30
0
    def test_initialize(self):
        # we don't use the dist from setUp because
        # we want to test before finalize is called
        dist = Distribution(attrs=self.attrs)
        bdist = dist.get_command_obj('bdist_prestoadmin')

        self.assertEquals(bdist.bdist_dir, None)
        self.assertEquals(bdist.dist_dir, None)
        self.assertEquals(bdist.virtualenv_version, None)
        self.assertEquals(bdist.keep_temp, False)
        self.assertEquals(bdist.online_install, False)
コード例 #31
0
def compile_c_module(cfiles, modbasename, eci, tmpdir=None):
    #try:
    #    from distutils.log import set_threshold
    #    set_threshold(10000)
    #except ImportError:
    #    print "ERROR IMPORTING"
    #    pass
    cfiles = [py.path.local(f) for f in cfiles]
    if tmpdir is None:
        tmpdir = udir.join("module_cache").ensure(dir=1)
    num = 0
    cfiles += eci.separate_module_files
    include_dirs = list(eci.include_dirs)
    include_dirs.append(py.path.local(pypydir).join('translator', 'c'))
    library_dirs = list(eci.library_dirs)
    if sys.platform == 'darwin':  # support Fink & Darwinports
        for s in ('/sw/', '/opt/local/'):
            if s + 'include' not in include_dirs and \
               os.path.exists(s + 'include'):
                include_dirs.append(s + 'include')
            if s + 'lib' not in library_dirs and \
               os.path.exists(s + 'lib'):
                library_dirs.append(s + 'lib')

    num = 0
    modname = modbasename
    while 1:
        if not tmpdir.join(modname + so_ext).check():
            break
        num += 1
        modname = '%s_%d' % (modbasename, num)

    lastdir = tmpdir.chdir()
    libraries = eci.libraries
    ensure_correct_math()
    try:
        if debug: print "modname", modname
        c = stdoutcapture.Capture(mixed_out_err=True)
        try:
            try:
                if compiler_command():
                    # GCC-ish options only
                    from distutils import sysconfig
                    gcv = sysconfig.get_config_vars()
                    cmd = compiler_command().replace('%s',
                                                     str(tmpdir.join(modname)))
                    for dir in [gcv['INCLUDEPY']] + list(include_dirs):
                        cmd += ' -I%s' % dir
                    for dir in library_dirs:
                        cmd += ' -L%s' % dir
                    os.system(cmd)
                else:
                    from distutils.dist import Distribution
                    from distutils.extension import Extension
                    from distutils.ccompiler import get_default_compiler
                    saved_environ = os.environ.items()
                    try:
                        # distutils.core.setup() is really meant for end-user
                        # interactive usage, because it eats most exceptions and
                        # turn them into SystemExits.  Instead, we directly
                        # instantiate a Distribution, which also allows us to
                        # ignore unwanted features like config files.
                        extra_compile_args = []
                        # ensure correct math on windows
                        if sys.platform == 'win32':
                            extra_compile_args.append(
                                '/Op')  # get extra precision
                        if get_default_compiler() == 'unix':
                            old_version = False
                            try:
                                g = os.popen('gcc --version', 'r')
                                verinfo = g.read()
                                g.close()
                            except (OSError, IOError):
                                pass
                            else:
                                old_version = verinfo.startswith('2')
                            if not old_version:
                                extra_compile_args.extend([
                                    "-Wno-unused-label", "-Wno-unused-variable"
                                ])
                        attrs = {
                            'name':
                            "testmodule",
                            'ext_modules': [
                                Extension(
                                    modname,
                                    [str(cfile) for cfile in cfiles],
                                    include_dirs=include_dirs,
                                    library_dirs=library_dirs,
                                    extra_compile_args=extra_compile_args,
                                    libraries=list(libraries),
                                )
                            ],
                            'script_name':
                            'setup.py',
                            'script_args':
                            ['-q', 'build_ext', '--inplace', '--force'],
                        }
                        dist = Distribution(attrs)
                        if not dist.parse_command_line():
                            raise ValueError, "distutils cmdline parse error"
                        dist.run_commands()
                    finally:
                        for key, value in saved_environ:
                            if os.environ.get(key) != value:
                                os.environ[key] = value
            finally:
                foutput, foutput = c.done()
                data = foutput.read()
                if data:
                    fdump = open("%s.errors" % modname, "w")
                    fdump.write(data)
                    fdump.close()
            # XXX do we need to do some check on fout/ferr?
            # XXX not a nice way to import a module
        except:
            print >> sys.stderr, data
            raise
    finally:
        lastdir.chdir()
    return str(tmpdir.join(modname) + so_ext)
コード例 #32
0
 def test_download_url(self):
     attrs = {'name': 'Boa', 'version': '3.0',
              'download_url': 'http://example.org/boa'}
     dist = Distribution(attrs)
     meta = self.format_metadata(dist)
     self.assertIn('Metadata-Version: 1.1', meta)
コード例 #33
0
>>> bc = _pylibmc.client([test_server], binary=True)
>>> bc.set("\0\0", "ORMOD")
True
>>> bc.get_multi(["\0\0"])
{'\x00\x00': 'ORMOD'}
"""

# Used to test pickling.
class Foo(object): pass

# Fix up sys.path so as to include the correct build/lib.*/ directory.
import sys
from distutils.dist import Distribution
from distutils.command.build import build

build_cmd = build(Distribution({"ext_modules": True}))
build_cmd.finalize_options()
lib_dirn = build_cmd.build_lib
sys.path.insert(0, lib_dirn)

import pylibmc, _pylibmc
import socket

__doc__ = pylibmc.__doc__ + "\n\n" + __doc__

# {{{ Ported cmemcache tests
import unittest

class TestCmemcached(unittest.TestCase):
    def setUp(self):
        self.mc = pylibmc.Client(["%s:%d" % (test_server[1:])])
コード例 #34
0
        'blasext.o', 'brent.o', 'comutil.o', 'misc.o', 'mnbrak.o', 'flxcomp.o',
        'flxdriv.o', 'flxread.o', 'flxwrit.o', 'grdcomp.o', 'grddriv.o',
        'grdinit.o', 'grdread.o', 'grdwrit.o', 'daspk.o', 'nksol.o',
        'svrut1.o', 'svrut2.o', 'svrut3.o', 'svrut4.o', 'vodpk.o', 'uoa.o',
        'dsum.o', 'dummy_py.o', 'error.o', 'getmsg.o', 'ssum.o', 'daux1.o',
        'wdf.o'
    ]

    if petsc:
        uedgeobjects = uedgeobjects + ['petsc-uedge.o', 'petscMod.o']

    if parallel:
        # add extra dot o's needed if we're parallel
        uedgeobjects = uedgeobjects + []
else:
    dummydist = Distribution()
    dummydist.parse_command_line()
    dummybuild = dummydist.get_command_obj('build')
    dummybuild.finalize_options()
    builddir = dummybuild.build_temp

uedgeobjects = map(lambda p: os.path.join(builddir, p), uedgeobjects)

if os.getenv('PACT_DIR') != None:
    library_dirs = fcompiler.libdirs + [
        os.path.join(os.getenv('PACT_DIR'), 'lib')
    ]
    libraries = ['pdb', 'pml', 'score', 'blas', 'm'] + fcompiler.libs
else:
    library_dirs = fcompiler.libdirs
    libraries = fcompiler.libs
コード例 #35
0
ファイル: dist.py プロジェクト: paradoxfxx/PyQwt
 def __init__(self, attrs=None):
     OldDistribution.__init__(self, attrs)
コード例 #36
0
 def test_announce(self):
     dist = Distribution()
     args = ('ok', )
     kwargs = {'level': 'ok2'}
     self.assertRaises(ValueError, dist.announce, args, kwargs)
コード例 #37
0
def distutils_scheme(dist_name,
                     user=False,
                     home=None,
                     root=None,
                     isolated=False,
                     prefix=None):
    """
    Return a distutils install scheme
    """
    from distutils.dist import Distribution

    scheme = {}

    if isolated:
        extra_dist_args = {"script_args": ["--no-user-cfg"]}
    else:
        extra_dist_args = {}
    dist_args = {'name': dist_name}
    dist_args.update(extra_dist_args)

    d = Distribution(dist_args)
    d.parse_config_files()
    i = d.get_command_obj('install', create=True)
    # NOTE: setting user or home has the side-effect of creating the home dir
    # or user base.css for installations during finalize_options()
    # ideally, we'd prefer a scheme class that has no side-effects.
    assert not (user and prefix), "user={} prefix={}".format(user, prefix)
    i.user = user or i.user
    if user:
        i.prefix = ""
    i.prefix = prefix or i.prefix
    i.home = home or i.home
    i.root = root or i.root
    i.finalize_options()
    for key in SCHEME_KEYS:
        scheme[key] = getattr(i, 'install_' + key)

    # install_lib specified in setup.cfg should install *everything*
    # into there (i.e. it takes precedence over both purelib and
    # platlib).  Note, i.install_lib is *always* set after
    # finalize_options(); we only want to override here if the user
    # has explicitly requested it hence going back to the config
    if 'install_lib' in d.get_option_dict('install'):
        scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))

    if running_under_virtualenv():
        scheme['headers'] = os.path.join(
            sys.prefix,
            'include',
            'site',
            'python' + sys.version[:3],
            dist_name,
        )

        if root is not None:
            path_no_drive = os.path.splitdrive(
                os.path.abspath(scheme["headers"]))[1]
            scheme["headers"] = os.path.join(
                root,
                path_no_drive[1:],
            )

    return scheme
コード例 #38
0
 def __init__(self, *args, **kwargs):
     self.configure_files = []
     self.configure_values = {}
     self.man_pages = []
     _Distribution.__init__(self, *args, **kwargs)
コード例 #39
0
 def _build_impl(self):
     dist = Distribution({
         "script_name": None,
         "script_args": ["build_ext"]
     })
     dist.ext_modules = cythonize([self.extension])
     dist.include_dirs = []
     dist.cmdclass = {'build_ext': custom_build_ext}
     build = dist.get_command_obj('build')
     # following the convention of cython's pyxbuild and naming
     # base directory "_pyxbld"
     build.build_base = join(self.CYMJ_DIR_PATH, 'generated',
                             '_pyxbld_%s' % (self.version))
     dist.parse_command_line()
     obj_build_ext = dist.get_command_obj("build_ext")
     dist.run_commands()
     built_so_file_path, = obj_build_ext.get_outputs()
     return built_so_file_path
コード例 #40
0
 def __init__(self, attrs=None):
     self.add_prefix = False
     self.remove_prefix = False
     Distribution.__init__(self, attrs)
コード例 #41
0
def test_pyscaffold_keyword():
    dist = Distribution()
    integration.pyscaffold_keyword(dist, "use_pyscaffold", True)
コード例 #42
0
ファイル: test_build.py プロジェクト: unixnut/rainbow
def generate_man_page(request):
    path = 'build/tests-workspace/manpage_' + request.node.name
    command = GenerateManPage(Distribution())
    setattr(command, 'output', path)
    command.run()
    return open(path).read()
コード例 #43
0
    def _build_extension_module(self, buildable):
        """ Build an extension module from the sources. """

        project = self.project

        set_threshold(INFO if project.verbose else ERROR)

        distribution = Distribution()

        module_builder = ExtensionCommand(distribution, buildable)
        module_builder.build_lib = buildable.build_dir
        module_builder.debug = buildable.debug

        if buildable.debug:
            # Enable assert().
            module_builder.undef = 'NDEBUG'

        module_builder.ensure_finalized()

        # Convert the #defines.
        define_macros = []
        for macro in buildable.define_macros:
            parts = macro.split('=', maxsplit=1)
            name = parts[0]
            try:
                value = parts[1]
            except IndexError:
                value = None

            define_macros.append((name, value))

        buildable.make_names_relative()

        module_builder.extensions = [
            Extension(buildable.fq_name,
                      buildable.sources,
                      define_macros=define_macros,
                      include_dirs=buildable.include_dirs,
                      libraries=buildable.libraries,
                      library_dirs=buildable.library_dirs)
        ]

        project.progress("Compiling the '{0}' module".format(
            buildable.fq_name))

        saved_cwd = os.getcwd()
        os.chdir(buildable.build_dir)

        try:
            module_builder.run()
        except Exception as e:
            raise UserException("Unable to compile the '{0}' module".format(
                buildable.fq_name),
                                detail=str(e))

        # Add the extension module to the buildable's list of installables.
        installable = Installable('module',
                                  target_subdir=buildable.get_install_subdir())
        installable.files.append(
            module_builder.get_ext_fullpath(buildable.fq_name))
        buildable.installables.append(installable)

        os.chdir(saved_cwd)
コード例 #44
0
ファイル: findInstallDir.py プロジェクト: alios/jsbsim
import sys, os
from distutils.dist import Distribution
from distutils.command.install import install

cmd = install(Distribution())
cmd.ensure_finalized()
path = cmd.install_lib

if "VIRTUAL_ENV" in os.environ:
    path = os.path.relpath(path, os.environ["VIRTUAL_ENV"])

sys.stdout.write(path)
コード例 #45
0
ファイル: setup.py プロジェクト: leejeonghun/py2exe-signable
 def __init__(self,attrs):
     self.interpreters = None
     Distribution.__init__(self,attrs)
コード例 #46
0
ファイル: test_cmd.py プロジェクト: 415ec080/finalPrj
 def setUp(self):
     dist = Distribution()
     self.cmd = MyCmd(dist)
コード例 #47
0
 def test_finalize_options(self):
     attrs = {'keywords': 'one,two', 'platforms': 'one,two'}
     dist = Distribution(attrs=attrs)
     dist.finalize_options()
     self.assertEqual(dist.metadata.platforms, ['one', 'two'])
     self.assertEqual(dist.metadata.keywords, ['one', 'two'])
コード例 #48
0
ファイル: rust_setuptools.py プロジェクト: kurhula/qpick
 def __init__(self, attrs=None):
     Distribution.__init__(self, attrs)
     self.ext_modules = []
コード例 #49
0
ファイル: dist.py プロジェクト: CZ-NIC/fred-utils-distutils
 def get_command_packages(self):
     pkgs = _Distribution.get_command_packages(self)
     if "freddist.command" not in self.command_packages:
         pkgs.insert(0, "freddist.command")
         self.command_packages = pkgs
     return pkgs
コード例 #50
0
 def __init__(self, attrs=None):
     self.coredata_files = None
     self.example_files = None
     self.document_files = None
     Distribution.__init__(self, attrs)
コード例 #51
0
 def __init__(self, *args):
     self.without_gettext = False
     Distribution.__init__(self, *args)
コード例 #52
0
 def has_ext_modules(self):
     # self.ext_modules is emptied in hgbuildpy.finalize_options which is
     # too late for some cases
     return not self.pure and Distribution.has_ext_modules(self)
コード例 #53
0
def install_connector(root_dir, install_dir, protobuf_include_dir,
                      protobuf_lib_dir, protoc, connc_location=None,
                      extra_compile_args=None, extra_link_args=None,
                      debug=False):
    """Install Connector/Python in working directory
    """
    logfile = 'myconnpy_install.log'
    LOGGER.info("Installing Connector/Python in {0}".format(install_dir))

    try:
        # clean up previous run
        if os.path.exists(logfile):
            os.unlink(logfile)
        shutil.rmtree(install_dir)
    except OSError:
        pass

    cmd = [
        sys.executable,
        'setup.py',
        'clean', '--all',  # necessary for removing the build/
    ]

    dist = Distribution()
    cmd_build = dist.get_command_obj('build')
    cmd_build.ensure_finalized()

    cmd.extend([
        'install',
        '--root', install_dir,
        '--install-lib', '.',
        '--static',
        '--is-wheel'
    ])
    if os.name == 'nt':
        cmd.extend([
            '--install-data', cmd_build.build_platlib
        ])

    if any((protobuf_include_dir, protobuf_lib_dir, protoc)):
        cmd.extend([
            '--with-protobuf-include-dir', protobuf_include_dir,
            '--with-protobuf-lib-dir', protobuf_lib_dir,
            '--with-protoc', protoc,
        ])

    if connc_location:
        cmd.extend(['--with-mysql-capi', connc_location])

    if extra_compile_args:
        cmd.extend(['--extra-compile-args', extra_compile_args])

    if extra_link_args:
        cmd.extend(['--extra-link-args', extra_link_args])

    LOGGER.debug("Installing command: {0}".format(cmd))
    prc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                           stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                           cwd=root_dir)
    stdout = prc.communicate()[0]
    if prc.returncode is not 0:
        with open(logfile, 'wb') as logfp:
            logfp.write(stdout)
        LOGGER.error("Failed installing Connector/Python, see {log}".format(
            log=logfile))
        if debug:
            with open(logfile) as logfr:
                print(logfr.read())
        sys.exit(1)
コード例 #54
0
ファイル: test_dist.py プロジェクト: termim/setuptools
 def test_obsoletes_to_list(self):
     attrs = {"name": "package", "obsoletes": iter(["other"])}
     dist = Distribution(attrs)
     self.assertIsInstance(dist.metadata.obsoletes, list)
コード例 #55
0
 def __init__(self, *args, **kwargs):
     self.package_data = None
     Distribution.__init__(self, *args, **kwargs)
コード例 #56
0
# serve to show the default.

import sys, os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# This should locate the parent directory for atomac
sys.path.insert(0, os.path.abspath('..'))

# Get info about the _a11y extension first
import distutils.command.build
from distutils.dist import Distribution

b = distutils.command.build.build(Distribution())
b.initialize_options()
b.finalize_options()

# Add to sys.path the path to the library build directory
# This will work only if the library has been built from commandline via
# python setup.py build
# TODO: Integrate building the _a11y module before building the docs
sys.path.insert(0, os.path.join(os.path.abspath('..'), b.build_platlib))

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
コード例 #57
0
 def test_classifier(self):
     attrs = {'name': 'Boa', 'version': '3.0',
              'classifiers': ['Programming Language :: Python :: 3']}
     dist = Distribution(attrs)
     meta = self.format_metadata(dist)
     self.assertIn('Metadata-Version: 1.1', meta)
コード例 #58
0
def distutils_scheme(
    dist_name, user=False, home=None, root=None, isolated=False, prefix=None
):
    # type:(str, bool, str, str, bool, str) -> Dict[str, str]
    """
    Return a distutils install scheme
    """
    from distutils.dist import Distribution

    dist_args = {'name': dist_name}  # type: Dict[str, Union[str, List[str]]]
    if isolated:
        dist_args["script_args"] = ["--no-user-cfg"]

    d = Distribution(dist_args)
    d.parse_config_files()
    obj = None  # type: Optional[DistutilsCommand]
    obj = d.get_command_obj('install', create=True)
    assert obj is not None
    i = cast(distutils_install_command, obj)
    # NOTE: setting user or home has the side-effect of creating the home dir
    # or user base for installations during finalize_options()
    # ideally, we'd prefer a scheme class that has no side-effects.
    assert not (user and prefix), f"user={user} prefix={prefix}"
    assert not (home and prefix), f"home={home} prefix={prefix}"
    i.user = user or i.user
    if user or home:
        i.prefix = ""
    i.prefix = prefix or i.prefix
    i.home = home or i.home
    i.root = root or i.root
    i.finalize_options()

    scheme = {}
    for key in SCHEME_KEYS:
        scheme[key] = getattr(i, 'install_' + key)

    # install_lib specified in setup.cfg should install *everything*
    # into there (i.e. it takes precedence over both purelib and
    # platlib).  Note, i.install_lib is *always* set after
    # finalize_options(); we only want to override here if the user
    # has explicitly requested it hence going back to the config
    if 'install_lib' in d.get_option_dict('install'):
        scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))

    if running_under_virtualenv():
        scheme['headers'] = os.path.join(
            i.prefix,
            'main',
            'site',
            f'python{get_major_minor_version()}',
            dist_name,
        )

        if root is not None:
            path_no_drive = os.path.splitdrive(
                os.path.abspath(scheme["headers"]))[1]
            scheme["headers"] = os.path.join(
                root,
                path_no_drive[1:],
            )

    return scheme
コード例 #59
0
ファイル: runbench.py プロジェクト: timgates42/pylibmc
def build_lib_dirname():
    from distutils.dist import Distribution
    from distutils.command.build import build
    build_cmd = build(Distribution({"ext_modules": True}))
    build_cmd.finalize_options()
    return build_cmd.build_lib
コード例 #60
0
import sys
from distutils.dist import Distribution
from distutils.extension import Extension
from distutils.command.build_ext import build_ext

ext = Extension('jsbsim', [])
name = build_ext(Distribution()).get_ext_filename(ext.name)

sys.stdout.write(name)