我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用distutils.core.Distribution()。
def create_dist(self, pkg_name='foo', **kw): """Will generate a test environment. This function creates: - a Distribution instance using keywords - a temporary directory with a package structure It returns the package directory and the distribution instance. """ tmp_dir = self.mkdtemp() pkg_dir = os.path.join(tmp_dir, pkg_name) os.mkdir(pkg_dir) dist = Distribution(attrs=kw) return pkg_dir, dist
def test_customize_compiler_before_get_config_vars(self): # Issue #21923: test that a Distribution compiler # instance can be called without an explicit call to # get_config_vars(). with open(TESTFN, 'w') as f: f.writelines(textwrap.dedent('''\ from distutils.core import Distribution config = Distribution().get_command_obj('config') # try_compile may pass or it may fail if no compiler # is found but it should not raise an exception. rc = config.try_compile('int x;') ''')) p = subprocess.Popen([str(sys.executable), TESTFN], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) outs, errs = p.communicate() self.assertEqual(0, p.returncode, "Subprocess failed: " + outs)
def test_saved_password(self): # file with no password self.write_file(self.rc, PYPIRC_NOPASSWORD) # make sure it passes dist = Distribution() cmd = upload(dist) cmd.finalize_options() self.assertEqual(cmd.password, None) # make sure we get it as well, if another command # initialized it at the dist level dist.password = 'xxx' cmd = upload(dist) cmd.finalize_options() self.assertEqual(cmd.password, 'xxx')
def test_default_settings(self): dist = Distribution() dist.command_obj["build"] = support.DummyCommand( build_scripts="/foo/bar") dist.command_obj["install"] = support.DummyCommand( install_scripts="/splat/funk", force=1, skip_build=1, ) cmd = install_scripts(dist) self.assertFalse(cmd.force) self.assertFalse(cmd.skip_build) self.assertIsNone(cmd.build_dir) self.assertIsNone(cmd.install_dir) cmd.finalize_options() self.assertTrue(cmd.force) self.assertTrue(cmd.skip_build) self.assertEqual(cmd.build_dir, "/foo/bar") self.assertEqual(cmd.install_dir, "/splat/funk")
def test_solaris_enable_shared(self): dist = Distribution({'name': 'xx'}) cmd = build_ext(dist) old = sys.platform sys.platform = 'sunos' # fooling finalize_options from distutils.sysconfig import _config_vars old_var = _config_vars.get('Py_ENABLE_SHARED') _config_vars['Py_ENABLE_SHARED'] = 1 try: cmd.ensure_finalized() finally: sys.platform = old if old_var is None: del _config_vars['Py_ENABLE_SHARED'] else: _config_vars['Py_ENABLE_SHARED'] = old_var # make sure we get some library dirs under solaris self.assertGreater(len(cmd.library_dirs), 0)
def setUp(self): """Patches the environment.""" super(PyPIRCCommandTestCase, self).setUp() self.tmp_dir = self.mkdtemp() os.environ['HOME'] = self.tmp_dir self.rc = os.path.join(self.tmp_dir, '.pypirc') self.dist = Distribution() class command(PyPIRCCommand): def __init__(self, dist): PyPIRCCommand.__init__(self, dist) def initialize_options(self): pass finalize_options = initialize_options self._cmd = command self.old_threshold = set_threshold(WARN)
def test_finalize_options(self): dist = Distribution({'name': 'xx'}) cmd = install(dist) # must supply either prefix/exec-prefix/home or # install-base/install-platbase -- not both cmd.prefix = 'prefix' cmd.install_base = 'base' self.assertRaises(DistutilsOptionError, cmd.finalize_options) # must supply either home or prefix/exec-prefix -- not both cmd.install_base = None cmd.home = 'home' self.assertRaises(DistutilsOptionError, cmd.finalize_options) # can't combine user with prefix/exec_prefix/home or # install_(plat)base cmd.prefix = None cmd.user = 'user' self.assertRaises(DistutilsOptionError, cmd.finalize_options)
def test_user_site(self): import site dist = Distribution({'name': 'xx'}) cmd = build_ext(dist) # making sure the user option is there options = [name for name, short, label in cmd.user_options] self.assertIn('user', options) # setting a value cmd.user = 1 # setting user based lib and include lib = os.path.join(site.USER_BASE, 'lib') incl = os.path.join(site.USER_BASE, 'include') os.mkdir(lib) os.mkdir(incl) cmd.ensure_finalized() # see if include_dirs and library_dirs were set self.assertIn(lib, cmd.library_dirs) self.assertIn(lib, cmd.rpath) self.assertIn(incl, cmd.include_dirs)
def _build(tmpdir, ext): # XXX compact but horrible :-( from distutils.core import Distribution import distutils.errors # dist = Distribution({'ext_modules': [ext]}) dist.parse_config_files() options = dist.get_option_dict('build_ext') options['force'] = ('ffiplatform', True) options['build_lib'] = ('ffiplatform', tmpdir) options['build_temp'] = ('ffiplatform', tmpdir) # try: dist.run_command('build_ext') except (distutils.errors.CompileError, distutils.errors.LinkError) as e: raise VerificationError('%s: %s' % (e.__class__.__name__, e)) # cmd_obj = dist.get_command_obj('build_ext') [soname] = cmd_obj.get_outputs() return soname
def _get_pypirc_command(self): """ Get the distutils command for interacting with PyPI configurations. :return: the command. """ from distutils.core import Distribution from distutils.config import PyPIRCCommand d = Distribution() return PyPIRCCommand(d)
def _build(tmpdir, ext, compiler_verbose=0): # XXX compact but horrible :-( from distutils.core import Distribution import distutils.errors, distutils.log # dist = Distribution({'ext_modules': [ext]}) dist.parse_config_files() options = dist.get_option_dict('build_ext') options['force'] = ('ffiplatform', True) options['build_lib'] = ('ffiplatform', tmpdir) options['build_temp'] = ('ffiplatform', tmpdir) # try: old_level = distutils.log.set_threshold(0) or 0 try: distutils.log.set_verbosity(compiler_verbose) dist.run_command('build_ext') cmd_obj = dist.get_command_obj('build_ext') [soname] = cmd_obj.get_outputs() finally: distutils.log.set_threshold(old_level) except (distutils.errors.CompileError, distutils.errors.LinkError) as e: raise VerificationError('%s: %s' % (e.__class__.__name__, e)) # return soname
def get_cmd(self, metadata=None): """Returns a cmd""" if metadata is None: metadata = {'name': 'fake', 'version': '1.0', 'url': 'xxx', 'author': 'xxx', 'author_email': 'xxx'} dist = Distribution(metadata) dist.script_name = 'setup.py' dist.packages = ['somecode'] dist.include_package_data = True cmd = sdist(dist) cmd.dist_dir = 'dist' return dist, cmd
def test_no_optimize_flag(self): # let's create a package that brakes bdist_rpm tmp_dir = self.mkdtemp() os.environ['HOME'] = tmp_dir # to confine dir '.rpmdb' creation pkg_dir = os.path.join(tmp_dir, 'foo') os.mkdir(pkg_dir) self.write_file((pkg_dir, 'setup.py'), SETUP_PY) self.write_file((pkg_dir, 'foo.py'), '#') self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py') self.write_file((pkg_dir, 'README'), '') dist = Distribution({'name': 'foo', 'version': '0.1', 'py_modules': ['foo'], 'url': 'xxx', 'author': 'xxx', 'author_email': 'xxx'}) dist.script_name = 'setup.py' os.chdir(pkg_dir) sys.argv = ['setup.py'] cmd = bdist_rpm(dist) cmd.fix_python = True cmd.quiet = 1 cmd.ensure_finalized() cmd.run() dist_created = os.listdir(os.path.join(pkg_dir, 'dist')) self.assertIn('foo-0.1-1.noarch.rpm', dist_created) # bug #2945: upload ignores bdist_rpm files self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files) self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files) os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm'))
def test_empty_package_dir(self): # See SF 1668596/1720897. cwd = os.getcwd() # create the distribution files. sources = self.mkdtemp() open(os.path.join(sources, "__init__.py"), "w").close() testdir = os.path.join(sources, "doc") os.mkdir(testdir) open(os.path.join(testdir, "testfile"), "w").close() os.chdir(sources) old_stdout = sys.stdout sys.stdout = StringIO.StringIO() try: dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": ""}, "package_data": {"pkg": ["doc/*"]}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.script_args = ["build"] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail("failed package_data test when package_dir is ''") finally: # Restore state. os.chdir(cwd) sys.stdout = old_stdout
def test_dir_in_package_data(self): """ A directory in package_data should not be added to the filelist. """ # See bug 19286 sources = self.mkdtemp() pkg_dir = os.path.join(sources, "pkg") os.mkdir(pkg_dir) open(os.path.join(pkg_dir, "__init__.py"), "w").close() docdir = os.path.join(pkg_dir, "doc") os.mkdir(docdir) open(os.path.join(docdir, "testfile"), "w").close() # create the directory that could be incorrectly detected as a file os.mkdir(os.path.join(docdir, 'otherdir')) os.chdir(sources) dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.script_args = ["build"] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail("failed package_data when data dir includes a dir")
def test_installation(self): source = self.mkdtemp() expected = [] def write_script(name, text): expected.append(name) f = open(os.path.join(source, name), "w") try: f.write(text) finally: f.close() write_script("script1.py", ("#! /usr/bin/env python2.3\n" "# bogus script w/ Python sh-bang\n" "pass\n")) write_script("script2.py", ("#!/usr/bin/python\n" "# bogus script w/ Python sh-bang\n" "pass\n")) write_script("shell.sh", ("#!/bin/sh\n" "# bogus shell script w/ sh-bang\n" "exit 0\n")) target = self.mkdtemp() dist = Distribution() dist.command_obj["build"] = support.DummyCommand(build_scripts=source) dist.command_obj["install"] = support.DummyCommand( install_scripts=target, force=1, skip_build=1, ) cmd = install_scripts(dist) cmd.finalize_options() cmd.run() installed = os.listdir(target) for name in expected: self.assertIn(name, installed)
def test_build_ext(self): global ALREADY_TESTED support.copy_xxmodule_c(self.tmp_dir) self.xx_created = True xx_c = os.path.join(self.tmp_dir, 'xxmodule.c') xx_ext = Extension('xx', [xx_c]) dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]}) dist.package_dir = self.tmp_dir cmd = build_ext(dist) support.fixup_build_ext(cmd) cmd.build_lib = self.tmp_dir cmd.build_temp = self.tmp_dir old_stdout = sys.stdout if not test_support.verbose: # silence compiler output sys.stdout = StringIO() try: cmd.ensure_finalized() cmd.run() finally: sys.stdout = old_stdout if ALREADY_TESTED: self.skipTest('Already tested in %s' % ALREADY_TESTED) else: ALREADY_TESTED = type(self).__name__ import xx for attr in ('error', 'foo', 'new', 'roj'): self.assertTrue(hasattr(xx, attr)) self.assertEqual(xx.foo(2, 5), 7) self.assertEqual(xx.foo(13,15), 28) self.assertEqual(xx.new().demo(), None) if test_support.HAVE_DOCSTRINGS: doc = 'This is a template module just for instruction.' self.assertEqual(xx.__doc__, doc) self.assertIsInstance(xx.Null(), xx.Null) self.assertIsInstance(xx.Str(), xx.Str)
def test_get_source_files(self): modules = [Extension('foo', ['xxx'])] dist = Distribution({'name': 'xx', 'ext_modules': modules}) cmd = build_ext(dist) cmd.ensure_finalized() self.assertEqual(cmd.get_source_files(), ['xxx'])