2019年6月28日 星期五

[ Python 常見問題 ] How to disable python warnings

Source From Here 
Question 
I am working with code that throws a lot of (for me at the moment) useless warnings using the warnings library. Reading (/scanning) the documentation I only found a way to disable warnings for single functions. But I don't want to change so much of the code. 

Is there maybe a flag like python -no-warning foo.py? 

What would you recommend? 

How-To 
For the command line, there's the -W option. 
# python -W ignore foo.py

You can also check the suppress warnings section of the python docs: 
If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:

For example: 
  1. import warnings  
  2.   
  3. def fxn():  
  4.     warnings.warn("deprecated", DeprecationWarning)  
  5.   
  6. with warnings.catch_warnings():  
  7.     warnings.simplefilter("ignore")  
  8.     fxn()  
I don't condone it, but you could just suppress all warnings with this: 
  1. import warnings  
  2. warnings.filterwarnings("ignore")  
Ex: 
>>> import warnings 
>>> def f(): 
... print('before') 
... warnings.warn('you are warned!') 
... print('after') 
>>> f() 
before 
__main__:3: UserWarning: you are warned! 
after
 
>>> warnings.filterwarnings("ignore") 
>>> f() 
before 
after
 


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...