python捕捉warning_Python warnings.warn方法代码示例
本文整理汇总了Python中warnings.warn方法的典型用法代码示例。如果您正苦于以下问题:Python warnings.warn方法的具体用法?Python warnings.warn怎么用?Python warnings.warn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块warnings的用法示例。
在下文中一共展示了warnings.warn方法的26个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: check_app_config_entries_dont_start_with_script_name
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def check_app_config_entries_dont_start_with_script_name(self):
"""Check for App config with sections that repeat script_name."""
for sn, app in cherrypy.tree.apps.items():
if not isinstance(app, cherrypy.Application):
continue
if not app.config:
continue
if sn == '':
continue
sn_atoms = sn.strip('/').split('/')
for key in app.config.keys():
key_atoms = key.strip('/').split('/')
if key_atoms[:len(sn_atoms)] == sn_atoms:
warnings.warn(
'The application mounted at %r has config '
'entries that start with its script name: %r' % (sn,
key))
开发者ID:cherrypy,项目名称:cherrypy,代码行数:19,
示例2: check_site_config_entries_in_app_config
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def check_site_config_entries_in_app_config(self):
"""Check for mounted Applications that have site-scoped config."""
for sn, app in cherrypy.tree.apps.items():
if not isinstance(app, cherrypy.Application):
continue
msg = []
for section, entries in app.config.items():
if section.startswith('/'):
for key, value in entries.items():
for n in ('engine.', 'server.', 'tree.', 'checker.'):
if key.startswith(n):
msg.append('[%s] %s = %s' %
(section, key, value))
if msg:
msg.insert(0,
'The application mounted at %r contains the '
'following config entries, which are only allowed '
'in site-wide config. Move them to a [global] '
'section and pass them to cherrypy.config.update() '
'instead of tree.mount().' % sn)
warnings.warn(os.linesep.join(msg))
开发者ID:cherrypy,项目名称:cherrypy,代码行数:24,
示例3: get_app
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def get_app(self, app=None):
"""Obtain a new (decorated) WSGI app to hook into the origin server."""
if app is None:
app = cherrypy.tree
if self.validate:
try:
from wsgiref import validate
except ImportError:
warnings.warn(
'Error importing wsgiref. The validator will not run.')
else:
# wraps the app in the validator
app = validate.validator(app)
return app
开发者ID:cherrypy,项目名称:cherrypy,代码行数:18,
示例4: pipe_fopen
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def pipe_fopen(command, mode, background=True):
if mode not in ["rb", "r"]:
raise RuntimeError("Now only support input from pipe")
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
def background_command_waiter(command, p):
p.wait()
if p.returncode != 0:
warnings.warn("Command \"{0}\" exited with status {1}".format(
command, p.returncode))
_thread.interrupt_main()
if background:
thread = threading.Thread(target=background_command_waiter,
args=(command, p))
# exits abnormally if main thread is terminated .
thread.daemon = True
thread.start()
else:
background_command_waiter(command, p)
return p.stdout
开发者ID:funcwj,项目名称:kaldi-python-io,代码行数:24,
示例5: fprop
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def fprop(self, x, y, **kwargs):
if self.attack is not None:
x = x, self.attack(x)
else:
x = x,
# Catching RuntimeError: Variable -= value not supported by tf.eager.
try:
y -= self.smoothing * (y - 1. / tf.cast(y.shape[-1], tf.float32))
except RuntimeError:
y.assign_sub(self.smoothing * (y - 1. / tf.cast(y.shape[-1],
tf.float32)))
logits = [self.model.get_logits(x, **kwargs) for x in x]
loss = sum(
softmax_cross_entropy_with_logits(labels=y,
logits=logit)
for logit in logits)
warnings.warn("LossCrossEntropy is deprecated, switch to "
"CrossEntropy. LossCrossEntropy may be removed on "
"or after 2019-03-06.")
return loss
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:24,
示例6: to_categorical
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def to_categorical(y, num_classes=None):
"""
Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to num_classes).
:param num_classes: num_classes: total number of classes.
:return: A binary matrix representation of the input.
"""
y = np.array(y, dtype='int').ravel()
if not num_classes:
num_classes = np.max(y) + 1
warnings.warn("FutureWarning: the default value of the second"
"argument in function \"to_categorical\" is deprecated."
"On 2018-9-19, the second argument"
"will become mandatory.")
n = y.shape[0]
categorical = np.zeros((n, num_classes))
categorical[np.arange(n), y] = 1
return categorical
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:22,
示例7: _get_logits_name
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def _get_logits_name(self):
"""
Looks for the name of the layer producing the logits.
:return: name of layer producing the logits
"""
softmax_name = self._get_softmax_name()
softmax_layer = self.model.get_layer(softmax_name)
if not isinstance(softmax_layer, Activation):
# In this case, the activation is part of another layer
return softmax_name
if hasattr(softmax_layer, 'inbound_nodes'):
warnings.warn(
"Please update your version to keras >= 2.1.3; "
"support for earlier keras versions will be dropped on "
"2018-07-22")
node = softmax_layer.inbound_nodes[0]
else:
node = softmax_layer._inbound_nodes[0]
logits_name = node.inbound_layers[0].name
return logits_name
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:26,
示例8: model_loss
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def model_loss(y, model, mean=True):
"""
Define loss of TF graph
:param y: correct labels
:param model: output of the model
:param mean: boolean indicating whether should return mean of loss
or vector of losses for each input of the batch
:return: return mean of loss if True, otherwise return vector with per
sample loss
"""
warnings.warn('This function is deprecated.')
op = model.op
if op.type == "Softmax":
logits, = op.inputs
else:
logits = model
out = softmax_cross_entropy_with_logits(logits=logits, labels=y)
if mean:
out = reduce_mean(out)
return out
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:24,
示例9: infer_devices
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def infer_devices(devices=None):
"""
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user does not specify this, infer_devices uses:
- All available GPUs, if there are any
- CPU otherwise
"""
if devices is None:
devices = get_available_gpus()
if len(devices) == 0:
warnings.warn("No GPUS, running on CPU")
# Set device to empy string, tf will figure out whether to use
# XLA or not, etc., automatically
devices = [""]
else:
assert len(devices) > 0
for device in devices:
assert isinstance(device, str), type(device)
return devices
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:24,
示例10: enable_receiving
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def enable_receiving(self):
"""
Switch the monitor into listing mode.
Connect to the event source and receive incoming events. Only after
calling this method, the monitor listens for incoming events.
.. note::
This method is implicitly called by :meth:`__iter__`. You don't
need to call it explicitly, if you are iterating over the
monitor.
.. deprecated:: 0.16
Will be removed in 1.0. Use :meth:`start()` instead.
"""
import warnings
warnings.warn('Will be removed in 1.0. Use Monitor.start() instead.',
DeprecationWarning)
self.start()
开发者ID:mbusb,项目名称:multibootusb,代码行数:22,
示例11: from_sys_path
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def from_sys_path(cls, context, sys_path): #pragma: no cover
"""
.. versionchanged:: 0.4
Raise :exc:`NoSuchDeviceError` instead of returning ``None``, if
no device was found for ``sys_path``.
.. versionchanged:: 0.5
Raise :exc:`DeviceNotFoundAtPathError` instead of
:exc:`NoSuchDeviceError`.
.. deprecated:: 0.18
Use :class:`Devices.from_sys_path` instead.
"""
import warnings
warnings.warn(
'Will be removed in 1.0. Use equivalent Devices method instead.',
DeprecationWarning,
stacklevel=2
)
return Devices.from_sys_path(context, sys_path)
开发者ID:mbusb,项目名称:multibootusb,代码行数:20,
示例12: traverse
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def traverse(self):
"""
Traverse all parent devices of this device from bottom to top.
Return an iterable yielding all parent devices as :class:`Device`
objects, *not* including the current device. The last yielded
:class:`Device` is the top of the device hierarchy.
.. deprecated:: 0.16
Will be removed in 1.0. Use :attr:`ancestors` instead.
"""
import warnings
warnings.warn(
'Will be removed in 1.0. Use Device.ancestors instead.',
DeprecationWarning,
stacklevel=2
)
return self.ancestors
开发者ID:mbusb,项目名称:multibootusb,代码行数:20,
示例13: __iter__
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def __iter__(self):
"""
Iterate over the names of all properties defined for this device.
Return a generator yielding the names of all properties of this
device as unicode strings.
.. deprecated:: 0.21
Will be removed in 1.0. Access properties with Device.properties.
"""
import warnings
warnings.warn(
'Will be removed in 1.0. Access properties with Device.properties.',
DeprecationWarning,
stacklevel=2
)
return self.properties.__iter__()
开发者ID:mbusb,项目名称:multibootusb,代码行数:19,
示例14: __getitem__
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def __getitem__(self, prop):
"""
Get the given property from this device.
``prop`` is a unicode or byte string containing the name of the
property.
Return the property value as unicode string, or raise a
:exc:`~exceptions.KeyError`, if the given property is not defined
for this device.
.. deprecated:: 0.21
Will be removed in 1.0. Access properties with Device.properties.
"""
import warnings
warnings.warn(
'Will be removed in 1.0. Access properties with Device.properties.',
DeprecationWarning,
stacklevel=2
)
return self.properties.__getitem__(prop)
开发者ID:mbusb,项目名称:multibootusb,代码行数:23,
示例15: asint
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def asint(self, prop):
"""
Get the given property from this device as integer.
``prop`` is a unicode or byte string containing the name of the
property.
Return the property value as integer. Raise a
:exc:`~exceptions.KeyError`, if the given property is not defined
for this device, or a :exc:`~exceptions.ValueError`, if the property
value cannot be converted to an integer.
.. deprecated:: 0.21
Will be removed in 1.0. Use Device.properties.asint() instead.
"""
import warnings
warnings.warn(
'Will be removed in 1.0. Use Device.properties.asint instead.',
DeprecationWarning,
stacklevel=2
)
return self.properties.asint(prop)
开发者ID:mbusb,项目名称:multibootusb,代码行数:24,
示例16: fit
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def fit(self, inputs, outputs, weights=None, override=False):
"""
Fit model.
Args:
inputs (list/Array): List/Array of input training objects.
outputs (list/Array): List/Array of output values
(supervisory signals).
weights (list/Array): List/Array of weights. Default to None,
i.e., unweighted.
override (bool): Whether to calculate the feature vectors
from given inputs. Default to False. Set to True if
you want to retrain the model with a different set of
training inputs.
"""
if self._xtrain is None or override:
xtrain = self.describer.describe_all(inputs)
else:
warnings.warn("Feature vectors retrieved from cache "
"and input training objects ignored. "
"To override the old cache with feature vectors "
"of new training objects, set override=True.")
xtrain = self._xtrain
self.model.fit(xtrain, outputs, weights)
self._xtrain = xtrain
开发者ID:materialsvirtuallab,项目名称:mlearn,代码行数:27,
示例17: predict
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def predict(self, inputs, override=False):
"""
Predict outputs with fitted model.
Args:
inputs (list/Array): List/Array of input testing objects.
override (bool): Whether to calculate the feature
vectors from given inputs. Default to False. Set to True
if you want to test the model with a different set of
testing inputs.
Returns:
Predicted output array from inputs.
"""
if self._xtest is None or override:
xtest = self.describer.describe_all(inputs)
else:
warnings.warn("Feature vectors retrieved from cache "
"and input testing objects ignored. "
"To override the old cache with feature vectors "
"of new testing objects, set override=True.")
xtest = self._xtest
self._xtest = xtest
return self.model.predict(xtest)
开发者ID:materialsvirtuallab,项目名称:mlearn,代码行数:26,
示例18: rc
点赞 6
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def rc():
'''
config.rc() yields the data imported from the Neuropythy rc file, if any.
'''
if config._rc is None:
# First: We check to see if we have been given a custom nptyhrc file:
npythyrc_path = os.path.expanduser('~/.npythyrc')
if 'NPYTHYRC' in os.environ:
npythyrc_path = os.path.expanduser(os.path.expandvars(os.environ['NPYTHYRC']))
# the default config:
if os.path.isfile(npythyrc_path):
try:
config._rc = loadrc(npythyrc_path)
config._rc['npythyrc_loaded'] = True
except Exception as err:
warnings.warn('Could not load neuropythy RC file: %s' % npythyrc_path)
config._rc = {'npythyrc_loaded':False,
'npythyrc_error': err}
else:
config._rc = {'npythyrc_loaded':False}
config._rc['npythyrc'] = npythyrc_path
return config._rc
开发者ID:noahbenson,项目名称:neuropythy,代码行数:24,
示例19: __setitem__
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def __setitem__(self, key, value):
if key not in self.agents or self.agents[key] is None:
self.agents[key] = value
if value is None:
warnings.warn("Trying to set the value of key {} to None.".
format(key), RuntimeWarning)
else:
pass
# this fails the tests at the moment, so we need to debug
# it is the tests that have a problem!
# raise KeyError("The key \"{}\" already exists in the registry"
# .format(key))
开发者ID:gcallah,项目名称:indras_net,代码行数:14,
示例20: _configure_logging
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def _configure_logging(level=logging.INFO):
logging.addLevelName(logging.DEBUG, 'Debug:')
logging.addLevelName(logging.INFO, 'Info:')
logging.addLevelName(logging.WARNING, 'Warning!')
logging.addLevelName(logging.CRITICAL, 'Critical!')
logging.addLevelName(logging.ERROR, 'Error!')
logging.basicConfig(format='%(levelname)s %(message)s', level=logging.INFO)
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
# TODO hack to get rid of deprecation warning that appeared allthough filters
# are set to ignore. Is there a more sane way?
warnings.warn = lambda *args, **kwargs: None
开发者ID:mme,项目名称:vergeml,代码行数:17,
示例21: add_member
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def add_member(self, login):
"""Add ``login`` to this team.
:returns: bool
"""
warnings.warn(
'This is no longer supported by the GitHub API, see '
'https://developer.github.com/changes/2014-09-23-one-more-week'
'-before-the-add-team-member-api-breaking-change/',
DeprecationWarning)
url = self._build_url('members', login, base_url=self._api)
return self._boolean(self._put(url), 204, 404)
开发者ID:kislyuk,项目名称:aegea,代码行数:14,
示例22: remove_member
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def remove_member(self, login):
"""Remove ``login`` from this team.
:param str login: (required), login of the member to remove
:returns: bool
"""
warnings.warn(
'This is no longer supported by the GitHub API, see '
'https://developer.github.com/changes/2014-09-23-one-more-week'
'-before-the-add-team-member-api-breaking-change/',
DeprecationWarning)
url = self._build_url('members', login, base_url=self._api)
return self._boolean(self._delete(url), 204, 404)
开发者ID:kislyuk,项目名称:aegea,代码行数:15,
示例23: _cleanup
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def _cleanup(cls, name, warn_message):
_rmtree(name)
_warnings.warn(warn_message, _ResourceWarning)
开发者ID:kislyuk,项目名称:aegea,代码行数:5,
示例24: isotropic_powerspectrum
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def isotropic_powerspectrum(*args, **kwargs): # pragma: no cover
"""
Deprecated function. See isotropic_power_spectrum doc
"""
import warnings
msg = "This function has been renamed and will disappear in the future."\
+" Please use isotropic_power_spectrum instead"
warnings.warn(msg, Warning)
return isotropic_power_spectrum(*args, **kwargs)
开发者ID:xgcm,项目名称:xrft,代码行数:11,
示例25: isotropic_crossspectrum
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def isotropic_crossspectrum(*args, **kwargs): # pragma: no cover
"""
Deprecated function. See isotropic_cross_spectrum doc
"""
import warnings
msg = "This function has been renamed and will disappear in the future."\
+" Please use isotropic_cross_spectrum instead"
warnings.warn(msg, Warning)
return isotropic_cross_spectrum(*args, **kwargs)
开发者ID:xgcm,项目名称:xrft,代码行数:11,
示例26: check_skipped_app_config
点赞 5
# 需要导入模块: import warnings [as 别名]
# 或者: from warnings import warn [as 别名]
def check_skipped_app_config(self):
"""Check for mounted Applications that have no config."""
for sn, app in cherrypy.tree.apps.items():
if not isinstance(app, cherrypy.Application):
continue
if not app.config:
msg = 'The Application mounted at %r has an empty config.' % sn
if self.global_config_contained_paths:
msg += (' It looks like the config you passed to '
'cherrypy.config.update() contains application-'
'specific sections. You must explicitly pass '
'application config via '
'cherrypy.tree.mount(..., config=app_config)')
warnings.warn(msg)
return
开发者ID:cherrypy,项目名称:cherrypy,代码行数:17,
注:本文中的warnings.warn方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。
python捕捉warning_Python warnings.warn方法代码示例相关推荐
- python logger.exception_Python logger.warn方法代码示例
本文整理汇总了Python中pip.log.logger.warn方法的典型用法代码示例.如果您正苦于以下问题:Python logger.warn方法的具体用法?Python logger.warn ...
- python args keargs_Python metrics.silhouette_score方法代码示例
本文整理汇总了Python中sklearn.metrics.silhouette_score方法的典型用法代码示例.如果您正苦于以下问题:Python metrics.silhouette_score ...
- python中summary_Python summary_pb2.Summary方法代码示例
本文整理汇总了Python中tensorflow.core.framework.summary_pb2.Summary方法的典型用法代码示例.如果您正苦于以下问题:Python summary_pb2 ...
- python cpu count_Python multiprocessing.cpu_count方法代码示例
本文整理汇总了Python中multiprocessing.cpu_count方法的典型用法代码示例.如果您正苦于以下问题:Python multiprocessing.cpu_count方法的具体用 ...
- python中weekday_Python calendar.weekday方法代码示例
本文整理汇总了Python中calendar.weekday方法的典型用法代码示例.如果您正苦于以下问题:Python calendar.weekday方法的具体用法?Python calendar. ...
- python logging logger_Python logging.Logger方法代码示例
本文整理汇总了Python中logging.Logger方法的典型用法代码示例.如果您正苦于以下问题:Python logging.Logger方法的具体用法?Python logging.Logge ...
- python里config_Python config.get_config方法代码示例
本文整理汇总了Python中config.get_config方法的典型用法代码示例.如果您正苦于以下问题:Python config.get_config方法的具体用法?Python config. ...
- doc python 颜色_Python wordcloud.ImageColorGenerator方法代码示例
本文整理汇总了Python中wordcloud.ImageColorGenerator方法的典型用法代码示例.如果您正苦于以下问题:Python wordcloud.ImageColorGenerat ...
- python asyncio future_Python asyncio.isfuture方法代码示例
本文整理汇总了Python中asyncio.isfuture方法的典型用法代码示例.如果您正苦于以下问题:Python asyncio.isfuture方法的具体用法?Python asyncio.i ...
- python operator __gt___Python operator.gt方法代码示例
本文整理汇总了Python中operator.gt方法的典型用法代码示例.如果您正苦于以下问题:Python operator.gt方法的具体用法?Python operator.gt怎么用?Pyth ...
最新文章
- Windows Server 2008正式版[微软官方下载地址+官方语言包]
- 运行Angular项目后自动打开网页
- Oracle数据库之PL/SQL
- .html?t=1a=2类似传递参数到flex中
- 100*100的 canvas 占多少内存?
- 进程创建fork-小代码
- linux中的网络体系结构
- 用C语言设置程序开机自启动
- mongodb java 多条件查询_MongoDB_Java连接mongo 使用Java多条件查询mongo数据
- 数据库索引的数据结构b+树
- 图像仿射变换之倾斜的python实现
- 英语学术论文写作概述
- MindManager 2020(Keymaker-CORE.rar)新手学习安装下载中文版及教程
- PDF文件太大怎么压缩,一分钟学会压缩PDF
- 我的世界服务器刷怪笼怎么修改,我的世界毒蜘蛛刷怪笼改造经验农场教学
- 习题3-5 三角形判断(15 分)
- java calendar getactualmaximum_Java Calendar
- 数据结构课程设计 校园导航系统
- 斗鱼直播弹幕python_python利用danmu实时获取斗鱼等直播网站字幕
- org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException : Unsupported major.minor versio
热门文章
- HNUST-C语言课程设计 完成质量测试记录·
- css flex布局iOS8兼容性问题
- 网线水晶头RJ45制作方法
- 互金舆情精选-2019/1/31
- 零信任是一次绝地反击
- 银联统一规范的收单业务消息域
- 再谈js拖拽(二)仿iGoogle自定义首页模块拖拽
- 新手怎么通过网络推广引流
- 一条SQL语句在MySQL中执行过程全解析
- 电源技术中的onsemi ESD5B5.0ST1G,ESD9B3.3ST5G,ESD9B5.0ST5G,SZESD9B5.0ST5G,ESD静电保护管 TVS管 电容值低,反应速度快的解决方案