我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用distutils.dist.Distribution()。
def test_empty_options(self): # an empty options dictionary should not stay in the # list of attributes # catching warnings warns = [] def _warn(msg): warns.append(msg) self.addCleanup(setattr, warnings, 'warn', warnings.warn) warnings.warn = _warn dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx', 'version': 'xxx', 'url': 'xxxx', 'options': {}}) self.assertEqual(len(warns), 0) self.assertNotIn('options', dir(dist))
def get_install_command(name): # late binding due to potential monkeypatching d = dist.Distribution({'name':name}) i = install.install(d) i.finalize_options() return i
def get_install_command(name): # late binding due to potential monkeypatching d = dist.Distribution({'name': name}) i = install.install(d) i.finalize_options() return i
def get_finalized_command(self, command, create=1): """Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object. """ cmd_obj = self.distribution.get_command_obj(command, create) cmd_obj.ensure_finalized() return cmd_obj # XXX rename to 'get_reinitialized_command()'? (should do the # same in dist.py, if so)
def run_command(self, command): """Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method. """ self.distribution.run_command(command)
def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1): """Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.)""" return file_util.copy_file( infile, outfile, preserve_mode, preserve_times, not self.force, link, dry_run=self.dry_run)
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
def setUp(self): dist = Distribution() self.cmd = MyCmd(dist)
def test_write_pkg_file(self): # Check DistributionMetadata handling of Unicode fields tmp_dir = self.mkdtemp() my_file = os.path.join(tmp_dir, 'f') klass = Distribution dist = klass(attrs={'author': u'Mister Café', 'name': 'my.package', 'maintainer': u'Café Junior', 'description': u'Café torréfié', 'long_description': u'Héhéhé'}) # let's make sure the file can be written # with Unicode fields. they are encoded with # PKG_INFO_ENCODING dist.metadata.write_pkg_file(open(my_file, 'w')) # regular ascii is of course always usable dist = klass(attrs={'author': 'Mister Cafe', 'name': 'my.package', 'maintainer': 'Cafe Junior', 'description': 'Cafe torrefie', 'long_description': 'Hehehe'}) my_file2 = os.path.join(tmp_dir, 'f2') dist.metadata.write_pkg_file(open(my_file2, 'w'))
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'])
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'])
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 = distutils.dist.Distribution() all_files = d.find_config_files() d = distutils.dist.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))
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)
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)
def test_long_description(self): long_desc = textwrap.dedent("""\ example:: We start here and continue here and end here.""") attrs = {"name": "package", "version": "1.0", "long_description": long_desc} dist = Distribution(attrs) meta = self.format_metadata(dist) meta = meta.replace('\n' + 8 * ' ', '\n') self.assertIn(long_desc, meta)
def test_simple_metadata(self): attrs = {"name": "package", "version": "1.0"} dist = Distribution(attrs) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.0", meta) self.assertNotIn("provides:", meta.lower()) self.assertNotIn("requires:", meta.lower()) self.assertNotIn("obsoletes:", meta.lower())
def test_provides_illegal(self): self.assertRaises(ValueError, Distribution, {"name": "package", "version": "1.0", "provides": ["my.pkg (splat)"]})
def test_requires(self): attrs = {"name": "package", "version": "1.0", "requires": ["other", "another (==1.0)"]} dist = Distribution(attrs) self.assertEqual(dist.metadata.get_requires(), ["other", "another (==1.0)"]) self.assertEqual(dist.get_requires(), ["other", "another (==1.0)"]) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.1", meta) self.assertNotIn("provides:", meta.lower()) self.assertIn("Requires: other", meta) self.assertIn("Requires: another (==1.0)", meta) self.assertNotIn("obsoletes:", meta.lower())
def test_requires_illegal(self): self.assertRaises(ValueError, Distribution, {"name": "package", "version": "1.0", "requires": ["my.pkg (splat)"]})
def test_obsoletes(self): attrs = {"name": "package", "version": "1.0", "obsoletes": ["other", "another (<1.0)"]} dist = Distribution(attrs) self.assertEqual(dist.metadata.get_obsoletes(), ["other", "another (<1.0)"]) self.assertEqual(dist.get_obsoletes(), ["other", "another (<1.0)"]) meta = self.format_metadata(dist) self.assertIn("Metadata-Version: 1.1", meta) self.assertNotIn("provides:", meta.lower()) self.assertNotIn("requires:", meta.lower()) self.assertIn("Obsoletes: other", meta) self.assertIn("Obsoletes: another (<1.0)", meta)
def test_obsoletes_illegal(self): self.assertRaises(ValueError, Distribution, {"name": "package", "version": "1.0", "obsoletes": ["my.pkg (splat)"]})
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)
def test_read_metadata(self): attrs = {"name": "package", "version": "1.0", "long_description": "desc", "description": "xxx", "download_url": "http://example.com", "keywords": ['one', 'two'], "requires": ['foo']} dist = Distribution(attrs) metadata = dist.metadata # write it then reloads it PKG_INFO = StringIO.StringIO() metadata.write_pkg_file(PKG_INFO) PKG_INFO.seek(0) metadata.read_pkg_file(PKG_INFO) self.assertEqual(metadata.name, "package") self.assertEqual(metadata.version, "1.0") self.assertEqual(metadata.description, "xxx") self.assertEqual(metadata.download_url, 'http://example.com') self.assertEqual(metadata.keywords, ['one', 'two']) self.assertEqual(metadata.platforms, ['UNKNOWN']) self.assertEqual(metadata.obsoletes, None) self.assertEqual(metadata.requires, ['foo'])
def get_command_class(opts, name): return opts['cmdclass'].get(name) or Distribution().get_command_class(name)
def setUp(self): super(BuildSphinxTest, self).setUp() self.useFixture(fixtures.MonkeyPatch( "sphinx.setup_command.BuildDoc.run", lambda self: None)) from distutils import dist self.distr = dist.Distribution() self.distr.packages = ("fake_package",) self.distr.command_options["build_sphinx"] = { "source_dir": ["a", "."]} pkg_fixture = fixtures.PythonPackage( "fake_package", [("fake_module.py", b""), ("another_fake_module_for_testing.py", b""), ("fake_private_module.py", b"")]) self.useFixture(pkg_fixture) self.useFixture(base.DiveDir(pkg_fixture.base)) self.distr.command_options["pbr"] = {} if hasattr(self, "excludes"): self.distr.command_options["pbr"]["autodoc_exclude_modules"] = ( 'setup.cfg', "fake_package.fake_private_module\n" "fake_package.another_fake_*\n" "fake_package.unknown_module") if self.has_opt: options = self.distr.command_options["pbr"] options["autodoc_index_modules"] = ('setup.cfg', self.autodoc)
def use_distribution(self, dist): if isinstance(dist, Distribution): self._conf = dist.get_option_dict(self._distutils_section) else: self._conf = dist
def __init__(self): from distutils.dist import Distribution self.distribution = Distribution() self.initialize_options()
def setUp(self): super(APIAutoDocTest, self).setUp() # setup_command requires the Sphinx instance to have some # attributes that aren't set normally with the way we use the # class (because we replace the constructor). Add default # values directly to the class definition. import sphinx.application sphinx.application.Sphinx.messagelog = [] sphinx.application.Sphinx.statuscode = 0 self.useFixture(fixtures.MonkeyPatch( "sphinx.application.Sphinx.__init__", lambda *a, **kw: None)) self.useFixture(fixtures.MonkeyPatch( "sphinx.application.Sphinx.build", lambda *a, **kw: None)) self.useFixture(fixtures.MonkeyPatch( "sphinx.application.Sphinx.config", _SphinxConfig)) self.useFixture(fixtures.MonkeyPatch( "sphinx.config.Config.init_values", lambda *a: None)) self.useFixture(fixtures.MonkeyPatch( "sphinx.config.Config.__init__", lambda *a: None)) from distutils import dist self.distr = dist.Distribution() self.distr.packages = ("fake_package",) self.distr.command_options["build_sphinx"] = { "source_dir": ["a", "."]} self.sphinx_options = self.distr.command_options["build_sphinx"] pkg_fixture = fixtures.PythonPackage( "fake_package", [("fake_module.py", b""), ("another_fake_module_for_testing.py", b""), ("fake_private_module.py", b"")]) self.useFixture(pkg_fixture) self.useFixture(base.DiveDir(pkg_fixture.base)) self.pbr_options = self.distr.command_options.setdefault('pbr', {}) self.pbr_options["autodoc_index_modules"] = ('setup.cfg', 'True')