Python pkg_resources 模块,require() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pkg_resources.require()。
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, ep.name, None)
if value is not None:
ep.require(installer=self.fetch_build_egg)
ep.load()(self, value)
if getattr(self, 'convert_2to3_doctests', None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def layout(self):
"""
"""
main_layout = QW.QVBoxLayout(self)
form_layout = QW.qformlayout()
version = pkg_resources.require("pytc-gui")[0].version
name_label = QW.QLabel("pytc: GUI")
name_font = name_label.font()
name_font.setPointSize(20)
name_label.setFont(name_font)
name_label.setAlignment(Qt.AlignCenter)
version_label = QW.QLabel("Version " + version)
version_font = version_label.font()
version_font.setPointSize(14)
version_label.setFont(version_font)
version_label.setAlignment(Qt.AlignCenter)
author_info = QW.QLabel("Hiranmayi Duvvuri,Mike Harms")
author_font = author_info.font()
author_font.setPointSize(10)
author_info.setFont(author_font)
OK_button = QW.QPushButton("OK", self)
OK_button.clicked.connect(self.close)
main_layout.addWidget(name_label)
main_layout.addWidget(version_label)
main_layout.addWidget(author_info)
main_layout.addWidget(OK_button)
self.setwindowTitle("About")
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def add_project_to_sys_path(self):
from pkg_resources import normalize_path, add_activation_listener
from pkg_resources import working_set, require
self.reinitialize_command('egg_info')
self.run_command('egg_info')
self.reinitialize_command('build_ext', inplace=1)
self.run_command('build_ext')
self.__old_path = sys.path[:]
self.__old_modules = sys.modules.copy()
if 'PyObjCTools' in sys.modules:
del sys.modules['PyObjCTools']
ei_cmd = self.get_finalized_command('egg_info')
sys.path.insert(0, normalize_path(ei_cmd.egg_base))
sys.path.insert(1, os.path.dirname(__file__))
add_activation_listener(lambda dist: dist.activate())
working_set.__init__()
require('%s==%s'%(ei_cmd.egg_name, ei_cmd.egg_version))
def parse_args_or_exit(argv=None):
"""
Parse command line options
"""
parser = argparse.ArgumentParser(
description='CLI util to dump an xml blob of the xapi database to json')
parser.add_argument('--version', action='version',
version="%%(prog)s %s" %
pkg_resources.require("xapitodict")[0].version)
parser.add_argument(
"-v", "--print-db-version", dest="print_db", action='store_true',
help="Include the version Metadata of the extracted xapi db "
"in the '_version' key")
parser.add_argument("xapi_db", Metavar="XAPIDB",
help="Path to the xml dump of the xapi database")
parser.add_argument("-o", "--output", Metavar="DEST",
dest="dest", default=None,
help="Path to the output json file. "
"Print to stdout when missing")
return parser.parse_args(argv)
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def main():
version = pkg_resources.require('hls2dash')[0].version
parser = argparse.ArgumentParser(
description="Rewrap a MPEG2 TS segment to a fragmented MP4"
,formatter_class=argparse.RawTextHelpformatter)
parser.add_argument('tsfile', Metavar='TSFILE', help='Path to TS file. Can be a URI or local file.')
parser.add_argument('output', Metavar='OUTPUT', help='Output file name')
parser.add_argument('--outdir', dest='outdir', default='.', help='Directory where the fragmented MP4 will be stored. Default is current directory')
parser.add_argument('--debug', dest='debug', default=False, help='Write debug info to stderr')
parser.add_argument('--version', version='%(prog)s ('+version+')')
args = parser.parse_args()
debug.doDebug = args.debug
ts = None
if re.match('^http', args.tsfile):
ts = TS.Remote(args.tsfile)
else:
ts = TS.Local(args.tsfile)
ts.remuxMP4(args.outdir, args.output)
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def version(self):
# Look at the version from setup.py
try:
airflow_version = pkg_resources.require("apache-airflow")[0].version
except Exception as e:
airflow_version = None
logging.error(e)
# Get the Git repo and git hash
git_version = None
try:
with open(os.path.join(*[settings.AIRFLOW_HOME, 'airflow', 'git_version'])) as f:
git_version = f.readline()
except Exception as e:
logging.error(e)
# Render information
title = "Version Info"
return self.render('airflow/version.html',
title=title,
airflow_version=airflow_version,
git_version=git_version)
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def test_get_version_setup(self):
def mock1(*args, **kwargs):
raise OSError
try:
backup1 = subprocess.check_output
except AttributeError:
backup1 = None
subprocess.check_output = mock1
def mock2(*args, **kwargs):
raise pkg_resources.distributionNotFound
backup2 = pkg_resources.require
pkg_resources.require = mock2
try:
self.assertEquals("0.0.0-unversioned", _get_version_setup())
finally:
if backup1:
subprocess.check_output = backup1
pkg_resources.require = backup2
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [
os.path.abspath(p)
for p in self.convert_2to3_doctests
]
else:
self.convert_2to3_doctests = []
def _require(options, file_config):
if not(options.require or
(file_config.has_section('require') and
file_config.items('require'))):
return
try:
import pkg_resources
except ImportError:
raise RuntimeError("setuptools is required for version requirements")
cmdline = []
for requirement in options.require:
pkg_resources.require(requirement)
cmdline.append(re.split('\s*(<!>=)', requirement, 1)[0])
if file_config.has_section('require'):
for label, requirement in file_config.items('require'):
if not label == db_label or label.startswith('%s.' % db_label):
continue
seen = [c for c in cmdline if requirement.startswith(c)]
if seen:
continue
pkg_resources.require(requirement)
def get_version():
"""
Utility to find the version of this application whatever the execution mode (cx_Freeze or normal)
:return:
"""
if getattr(sys, "frozen", False):
# this is cx_Freeze execution mode >> access our generated file
datadir = os.path.dirname(sys.executable)
path = os.path.join(datadir, version_file_cx_freeze)
with open(path, 'rt') as f:
return f.read()
else:
import pkg_resources # part of setuptools
from pkg_resources import distributionNotFound
try:
return pkg_resources.require("envswitch")[0].version
except distributionNotFound as e:
# this may happen if the module has not been even locally installed with "pip install ."
from setuptools_scm import get_version
return get_version()
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15):
to_dir = os.path.abspath(to_dir)
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.distributionNotFound:
return _do_download(version, download_delay)
except pkg_resources.VersionConflict as VC_err:
if imported:
msg = textwrap.dedent("""
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first,using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
""").format(VC_err=VC_err, version=version)
sys.stderr.write(msg)
sys.exit(2)
# otherwise,reload ok
del pkg_resources, sys.modules['pkg_resources']
return _do_download(version, download_delay)
def get_command_class(self, command):
"""Pluggable version of get_command_class()"""
if command in self.cmdclass:
return self.cmdclass[command]
eps = pkg_resources.iter_entry_points('distutils.commands', command)
for ep in eps:
ep.require(installer=self.fetch_build_egg)
self.cmdclass[command] = cmdclass = ep.load()
return cmdclass
else:
return _distribution.get_command_class(self, command)
def use_setuptools(version=DEFAULT_VERSION, download_delay)
def use_setuptools(
version=DEFAULT_VERSION,
to_dir=DEFAULT_SAVE_DIR, download_delay=15):
"""
Ensure that a setuptools version is installed.
Return None. Raise SystemExit if the requested version
or later cannot be installed.
"""
to_dir = os.path.abspath(to_dir)
# prior to importing,capture the module state for
# representative modules.
rep_modules = 'pkg_resources', 'setuptools'
imported = set(sys.modules).intersection(rep_modules)
try:
import pkg_resources
pkg_resources.require("setuptools>=" + version)
# a suitable version is already installed
return
except ImportError:
# pkg_resources not available; setuptools is not installed; download
pass
except pkg_resources.distributionNotFound:
# no version of setuptools was found; allow download
pass
except pkg_resources.VersionConflict as VC_err:
if imported:
_conflict_bail(VC_err, version)
# otherwise,unload pkg_resources to allow the downloaded version to
# take precedence.
del pkg_resources
_unload_pkg_resources()
return _do_download(version, download_delay)
def use_setuptools(version=DEFAULT_VERSION, download_delay)
def use_setuptools(version=DEFAULT_VERSION, download_delay)
def use_setuptools(version=DEFAULT_VERSION, download_delay)
def use_setuptools(version=DEFAULT_VERSION,
to_dir=os.curdir, download_delay=15):
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
was_imported = 'pkg_resources' in sys.modules or \
'setuptools' in sys.modules
try:
import pkg_resources
except ImportError:
return _do_download(version, download_delay)
try:
pkg_resources.require("setuptools>=" + version)
return
except pkg_resources.VersionConflict:
e = sys.exc_info()[1]
if was_imported:
sys.stderr.write(
"The required version of setuptools (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first,using\n"
"'easy_install -U setuptools'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return _do_download(version,
download_delay)
except pkg_resources.distributionNotFound:
return _do_download(version,
download_delay)
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self,ep.name,None)
if value is not None:
ep.require(installer=self.fetch_build_egg)
ep.load()(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests]
else:
self.convert_2to3_doctests = []
def get_command_class(self, command):
"""Pluggable version of get_command_class()"""
if command in self.cmdclass:
return self.cmdclass[command]
for ep in pkg_resources.iter_entry_points('distutils.commands',command):
ep.require(installer=self.fetch_build_egg)
self.cmdclass[command] = cmdclass = ep.load()
return cmdclass
else:
return _distribution.get_command_class(self, command)
def installation_report(self, req, dist, what="Installed"):
"""Helpful installation message for display to package users"""
msg = "\n%(what)s %(eggloc)s%(extras)s"
if self.multi_version and not self.no_report:
msg += """
Because this distribution was installed --multi-version,before you can
import modules from this package in an application,you will need to
'import pkg_resources' and then use a 'require()' call similar to one of
these examples,in order to select the desired version:
pkg_resources.require("%(name)s") # latest installed version
pkg_resources.require("%(name)s==%(version)s") # this exact version
pkg_resources.require("%(name)s>=%(version)s") # this version or higher
"""
if self.install_dir not in map(normalize_path,sys.path):
msg += """
Note also that the installation directory must be on sys.path at runtime for
this to work. (e.g. by being the application's script directory,by being on
PYTHONPATH,or by being added to sys.path by your code.)
"""
eggloc = dist.location
name = dist.project_name
version = dist.version
extras = '' # Todo: self.report_extras(req,dist)
return msg % locals()
def main():
"""
Main function,staring GUI.
"""
version = pkg_resources.require("pytc-gui")[0].version
try:
app = QW.QApplication(sys.argv)
app.setApplicationName("pytc")
app.setApplicationVersion(version)
pytc_run = MainWindow(app)
sys.exit(app.exec_())
except KeyboardInterrupt:
sys.exit()
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests]
else:
self.convert_2to3_doctests = []
def get_command_class(self, command):
ep.require(installer=self.fetch_build_egg)
self.cmdclass[command] = cmdclass = ep.load()
return cmdclass
else:
return _distribution.get_command_class(self, command)
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests]
else:
self.convert_2to3_doctests = []
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests]
else:
self.convert_2to3_doctests = []
def finalize_options(self):
_distribution.finalize_options(self)
if self.features:
self._set_global_opts_from_features()
for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
value = getattr(self, None):
# XXX may convert to set here when we can rely on set being builtin
self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests]
else:
self.convert_2to3_doctests = []