本文整理汇总了Python中packaging.version.parse方法的典型用法代码示例。如果您正苦于以下问题:Python version.parse方法的具体用法?Python version.parse怎么用?Python version.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类packaging.version
的用法示例。
在下文中一共展示了version.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_version
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def check_version(version):
"""Return version of package on pypi.python.org using json."""
def check(version):
try:
url_pattern = 'https://pypi.python.org/pypi/mdeepctr/json'
req = requests.get(url_pattern)
latest_version = parse('0')
version = parse(version)
if req.status_code == requests.codes.ok:
j = json.loads(req.text.encode('utf-8'))
releases = j.get('releases', [])
for release in releases:
ver = parse(release)
if not ver.is_prerelease:
latest_version = max(latest_version, ver)
if latest_version > version:
logging.warning('\nDeepCTR version {0} detected. Your version is {1}.\nUse `pip install -U mdeepctr` to upgrade.Changelog: https://github.com/shenweichen/DeepCTR/releases/tag/v{0}'.format(
latest_version, version))
except Exception:
return
Thread(target=check, args=(version,)).start()
示例2: keras_should_run_eagerly
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def keras_should_run_eagerly(request):
"""Fixture to run in graph and two eager modes.
The modes are:
- Graph mode
- TensorFlow eager and Keras eager
- TensorFlow eager and Keras not eager
The `tf.context` sets graph/eager mode for TensorFlow. The yield is True if Keras
should run eagerly.
"""
if request.param == "graph":
if version.parse(tf.__version__) >= version.parse("2"):
pytest.skip("Skipping graph mode for TensorFlow 2+.")
with context.graph_mode():
yield
else:
with context.eager_mode():
yield request.param == "tf_keras_eager"
示例3: main
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def main(args):
with open(args.config) as f:
if version.parse(yaml.version >= "5.1"):
config = yaml.load(f, Loader=yaml.FullLoader)
else:
config = yaml.load(f)
for k, v in config.items():
setattr(args, k, v)
# exp path
if not hasattr(args, 'exp_path'):
args.exp_path = os.path.dirname(args.config)
# dist init
if mp.get_start_method(allow_none=True) != 'spawn':
mp.set_start_method('spawn', force=True)
dist_init(args.launcher, backend='nccl')
# train
trainer = Trainer(args)
trainer.run()
示例4: main
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def main():
exp_dir = os.path.dirname(args.config)
with open(args.config) as f:
if version.parse(yaml.version >= "5.1"):
config = yaml.load(f, Loader=yaml.FullLoader)
else:
config = yaml.load(f)
for k, v in config.items():
setattr(args, k, v)
model = models.modules.__dict__[args.model['module']['arch']](args.model['module'])
model = torch.nn.DataParallel(model)
ckpt_path = exp_dir + '/checkpoints/ckpt_iter_{}.pth.tar'.format(args.iter)
save_path = exp_dir + '/checkpoints/convert_iter_{}.pth.tar'.format(args.iter)
ckpt = torch.load(ckpt_path)
weight = ckpt['state_dict']
model.load_state_dict(weight, strict=True)
model = model.module.image_encoder
torch.save(model.state_dict(), save_path)
示例5: _collect_migrations
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def _collect_migrations(project):
schema_version = version.parse(SCHEMA_VERSION)
def config_schema_version():
return version.parse(project._config['schema_version'])
if config_schema_version() > schema_version:
# Project config schema version is newer and therefore not supported.
raise RuntimeError(
"The signac schema version used by this project is {}, but signac {} "
"only supports up to schema version {}. Try updating signac.".format(
config_schema_version, __version__, SCHEMA_VERSION))
while config_schema_version() < schema_version:
for (origin, destination), migration in MIGRATIONS.items():
if version.parse(origin) == config_schema_version():
yield (origin, destination), migration
break
else:
raise RuntimeError(
"The signac schema version used by this project is {}, but signac {} "
"uses schema version {} and does not know how to migrate.".format(
config_schema_version(), __version__, schema_version))
示例6: _check_schema_compatibility
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def _check_schema_compatibility(self):
"""Checks whether this project's data schema is compatible with this version.
:raises RuntimeError:
If the schema version is incompatible.
"""
schema_version = version.parse(SCHEMA_VERSION)
config_schema_version = version.parse(self.config['schema_version'])
if config_schema_version > schema_version:
# Project config schema version is newer and therefore not supported.
raise IncompatibleSchemaVersion(
"The signac schema version used by this project is '{}', but signac {} "
"only supports up to schema version '{}'. Try updating signac.".format(
config_schema_version, __version__, schema_version))
elif config_schema_version < schema_version:
raise IncompatibleSchemaVersion(
"The signac schema version used by this project is '{}', but signac {} "
"requires schema version '{}'. Please use '$ signac migrate' to "
"irreversibly migrate this project's schema to the supported "
"version.".format(
config_schema_version, __version__, schema_version))
else: # identical and therefore compatible
logger.debug(
"The project's schema version {} is supported.".format(
config_schema_version))
示例7: check_versions
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def check_versions():
anndata_version = pkg_version("anndata")
umap_version = pkg_version("umap-learn")
if anndata_version < version.parse('0.6.10'):
from . import __version__
raise ImportError(
f'Scanpy {__version__} needs anndata version >=0.6.10, '
f'not {anndata_version}.\nRun `pip install anndata -U --no-deps`.'
)
if umap_version < version.parse('0.3.0'):
from . import __version__
# make this a warning, not an error
# it might be useful for people to still be able to run it
logg.warning(
f'Scanpy {__version__} needs umap ' f'version >=0.3.0, not {umap_version}.'
)
示例8: clean_requires_python
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def clean_requires_python(candidates):
"""Get a cleaned list of all the candidates with valid specifiers in the `requires_python` attributes."""
all_candidates = []
sys_version = ".".join(map(str, sys.version_info[:3]))
from packaging.version import parse as parse_version
py_version = parse_version(os.environ.get("PIP_PYTHON_VERSION", sys_version))
for c in candidates:
requires_python = _get_requires_python(c)
if requires_python:
# Old specifications had people setting this to single digits
# which is effectively the same as '>=digit,<digit+1'
if requires_python.isdigit():
requires_python = ">={0},<{1}".format(
requires_python, int(requires_python) + 1
)
try:
specifierset = SpecifierSet(requires_python)
except InvalidSpecifier:
continue
else:
if not specifierset.contains(py_version):
continue
all_candidates.append(c)
return all_candidates
示例9: read_config
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def read_config(fname):
if not (fname and os.path.isfile(fname)):
print("ERROR: config file %s not found."%fname)
return defaultdict(dict)
try:
with open(fname, 'rb') as ifile:
config = json.load(ifile)
except json.decoder.JSONDecodeError as err:
print("FATAL ERROR:")
print("\tCouldn't parse the JSON file {}".format(fname))
print("\tError message: '{}'".format(err.msg))
print("\tLine number: '{}'".format(err.lineno))
print("\tColumn number: '{}'".format(err.colno))
print("\tYou must correct this file in order to proceed.")
sys.exit(2)
return config
示例10: is_augur_version_compatable
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def is_augur_version_compatable(version):
"""
Checks if the provided **version** is the same major version
as the currently running version of augur.
Parameters
----------
version : str
version to check against the current version
Returns
-------
Bool
"""
current_version = packaging_version.parse(get_augur_version())
this_version = packaging_version.parse(version)
return this_version.release[0] == current_version.release[0]
示例11: doctor
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def doctor(args):
ver = dckr.version()['Version']
if ver.endswith('-ce'):
curr_version = version.parse(ver.replace('-ce', ''))
else:
curr_version = version.parse(ver)
min_version = version.parse('1.9.0')
ok = curr_version >= min_version
print 'docker version ... {1} ({0})'.format(ver, 'ok' if ok else 'update to {} at least'.format(min_version))
print 'bgperf image',
if img_exists('bgperf/exabgp'):
print '... ok'
else:
print '... not found. run `bgperf prepare`'
for name in ['gobgp', 'bird', 'quagga', 'frr']:
print '{0} image'.format(name),
if img_exists('bgperf/{0}'.format(name)):
print '... ok'
else:
print '... not found. if you want to bench {0}, run `bgperf prepare`'.format(name)
print '/proc/sys/net/ipv4/neigh/default/gc_thresh3 ... {0}'.format(gc_thresh3())
示例12: ensure_model_compatibility
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def ensure_model_compatibility(metadata, version_to_check=None):
from packaging import version
if version_to_check is None:
version_to_check = constants.MINIMUM_COMPATIBLE_VERSION
model_version = metadata.get("rasa", "0.0.0")
if version.parse(model_version) < version.parse(version_to_check):
raise UnsupportedDialogueModelError(
"The model version is to old to be "
"loaded by this Rasa Core instance. "
"Either retrain the model, or run with"
"an older version. "
"Model version: {} Instance version: {} "
"Minimal compatible version: {}"
"".format(model_version, rasa.__version__,
version_to_check),
model_version)
示例13: create_pointcloud_lopocs_table
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def create_pointcloud_lopocs_table(cls):
'''
Create some meta tables that stores informations used by lopocs to
stream patches in various formats
This function uses "packaging.version.parse" to evaluate the current
postgres version; depending on the system, it may returns verbose
answers like "X.X.X (Ubuntu X.X-Xubuntu0.18.04.1)". One has to split
this to keep only the simple version format.
'''
# to_regclass function changed its signature in postgresql >= 9.6
full_server_version = cls.query('show server_version')[0][0]
server_version = server_version_full.split()[0] # Keep only "X.X.X"
if version.parse(server_version) < version.parse('9.6.0'):
cls.execute("""
create or replace function to_regclass(text) returns regclass
language sql as 'select to_regclass($1::cstring)'
""")
cls.execute(LOPOCS_TABLES_QUERY)
示例14: api_version
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def api_version(self):
# API location changes between versions
# http://kubernetes.io/docs/user-guide/horizontal-pod-autoscaling/#api-object
if self.version() >= parse("1.3.0"):
return 'autoscaling/v1'
# 1.2 and older
return 'extensions/v1beta1'
示例15: wait
# 需要导入模块: from packaging import version [as 别名]
# 或者: from packaging.version import parse [as 别名]
def wait(self, namespace, name):
# fetch HPA details
hpa = self.hpa.get(namespace, name).json()
# FIXME all of the below can be replaced with hpa['status'][desiredReplicas']
# when https://github.com/kubernetes/kubernetes/issues/29739 is fixed
# until then we have to query things ourselves
# only wait 30 seconds / attempts - this is not optimal
# ideally it would use the resources wait commands but they vary
for _ in range(30):
# fetch resource attached to it
if self.version() >= parse("1.3.0"):
resource_kind = hpa['spec']['scaleTargetRef']['kind'].lower()
resource_name = hpa['spec']['scaleTargetRef']['name']
elif self.version() <= parse("1.2.0"):
resource_kind = hpa['spec']['scaleRef']['kind'].lower()
resource_name = hpa['spec']['scaleRef']['name']
resource = getattr(self, resource_kind)
resource = getattr(resource, 'get')(namespace, resource_name).json()
# compare resource current replica count to HPA
# (Deployment vs RC vs RS is all different)
if resource_kind in ['replicationcontroller', 'replicaset']:
replicas = resource['status']['replicas']
elif resource_kind == 'deployment':
replicas = resource['status']['availableReplicas']
if replicas <= hpa['spec']['maxReplicas'] or replicas >= hpa['spec']['minReplicas']:
break