python – 禁用源自scipy的警告
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 禁用源自scipy的警告,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2692字,纯文字阅读大概需要4分钟。
内容图文
当我将函数集成在不同的参数值时,我经常遇到如下错误:
lsoda-- warning..internal t (=r1) and h (=r2) are
such that in the machine, t + h = t on the next step
(h = step size). solver will continue anyway
虽然我理解错误的技术方面,但我不知道如何抑制它被打印到stdout.我查看了numpy.seterr(),但由于此错误消息似乎是从底层的C / Fortran代码生成的,因此它没有任何效果.而python script.py> / dev / null是有效的,它显然也隐藏了可能打印的其他有用信息.
有没有办法禁用这些lsoda警告和错误,或以其他方式阻止它们打印到stdout?
解决方法:
使用J.F. Sebastian’s stdout_redirected,您可以将文件描述符级别的stdout重定向到os.devnull.
with stdout_redirected():
soln2 = integrate.odeint(f, y2, t2, mxstep = 5000)
在with-statement之外,stdout仍然被打印出来.在套件内部,stdout被抑制.
例如,这里是Caeiro’s odeint example,使用stdout_redirected抑制了lsoda警告.
import os
import sys
import contextlib
import numpy as np
import scipy.integrate as integrate
from numpy import pi
def fileno(file_or_fd):
fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
if not isinstance(fd, int):
raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
return fd
@contextlib.contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
"""
https://stackoverflow.com/a/22434262/190597 (J.F. Sebastian)
"""
if stdout is None:
stdout = sys.stdout
stdout_fd = fileno(stdout)
# copy stdout_fd before it is overwritten
#NOTE: `copied` is inheritable on Windows when duplicating a standard stream
with os.fdopen(os.dup(stdout_fd), 'wb') as copied:
stdout.flush() # flush library buffers that dup2 knows nothing about
try:
os.dup2(fileno(to), stdout_fd) # $exec >&to
except ValueError: # filename
with open(to, 'wb') as to_file:
os.dup2(to_file.fileno(), stdout_fd) # $exec > to
try:
yield stdout # allow code to be run with the redirected stdout
finally:
# restore stdout to its previous value
#NOTE: dup2 makes stdout_fd inheritable unconditionally
stdout.flush()
os.dup2(copied.fileno(), stdout_fd) # $exec >&copied
#Constants and parameters
alpha=1/137.
k=1.e-9
T=40.
V= 6.e-6
r = 6.9673e12
u = 1.51856e7
#defining dy/dt's
def f(y, t):
A, B, C, D, E = y
# the model equations
f0 = 1.519e21*(-2*k/T*(k - (alpha/pi)*(B+V))*A)
f1 = ((3*B**2 + 3*C**2 + 6*B*C + 2*pi**2*B*T + pi**2*T**2)**-1
*(-f0*alpha/(3*pi**3) - 2*r*(B**3 + 3*B*C**2 + pi**2*T**2*B)
- u*(D**3 - E**3)))
f2 = u*(D**3 - E**3)/(3*C**2)
f3 = -u*(D**3 - E**3)/(3*D**2)
f4 = u*(D**3 - E**3)/(3*E**2) + r*(B**3 + 3*B*C**2 + pi**2*T**2*B)/(3*E**2)
return [f0, f1, f2, f3, f4]
t = np.linspace(1e-15, 1e-10, 1000000) # time grid
y2 = [2e13, 0, 50, 50, 25]
t2 = np.linspace(1.e-10, 1.e-5, 1000000)
with stdout_redirected():
soln2 = integrate.odeint(f, y2, t2, mxstep = 5000)
lsoda写入stdout的警告被抑制.
内容总结
以上是互联网集市为您收集整理的python – 禁用源自scipy的警告全部内容,希望文章能够帮你解决python – 禁用源自scipy的警告所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。