web-dev-qa-db-ja.com

Pythonの非推奨の警告を無視する方法

私はこれを得続けます:

DeprecationWarning: integer argument expected, got float

このメッセージを消すにはどうすればよいですか? Pythonで警告を回避する方法はありますか?

143
Mohammed

warningsモジュール のドキュメントから:

 #!/usr/bin/env python -W ignore::DeprecationWarning

Windowsを使用している場合:-W ignore::DeprecationWarningをPythonの引数として渡します。ただし、 int にキャストすることで、問題を解決できます。

(Python 3.2では、非推奨の警告はデフォルトで無視されることに注意してください。)

105
Stephan202

私はこれらを持っていました:

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.Egg/twisted/persisted/sob.py:12:
DeprecationWarning: the md5 module is deprecated; use hashlib instead import os, md5, sys

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.Egg/twisted/python/filepath.py:12:
DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha

以下で修正:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import md5, sha

yourcode()

これで、他のすべてのDeprecationWarningsを取得できますが、次の原因によるものは取得できません。

import md5, sha
177
Eddy Pronk

コードを修正する必要がありますが、念のため、

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning) 
172
ismail

これを行う最もクリーンな方法(特にWindows)は、C:\ Python26\Lib\site-packages\sitecustomize.pyに次を追加することで見つかりました。

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

このファイルを作成しなければならなかったことに注意してください。もちろん、異なる場合は、パスをpythonに変更します。

26

これらの答えはどれも役に立たなかったので、これを解決する方法を投稿します。次のat the beginning of my main.pyスクリプトを使用すると、問題なく動作します。


以下をそのまま使用します(コピーして貼り付けます)。

import "blabla"
import "blabla"

def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn

# more code here...
# more code here...

19
serafeim

正しい引数を渡しますか? :P

より深刻な注意事項として、コマンドラインで引数-Wi :: DeprecationWarningをインタープリターに渡して、非推奨の警告を無視することができます。

6
shylent

引数をintに変換します。それは次のように簡単です

int(argument)
5
Gonzalo Quero

関数でのみ警告を無視する場合、次のことができます。

import warnings
from functools import wraps


def ignore_warnings(f):
    @wraps(f)
    def inner(*args, **kwargs):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            response = f(*args, **kwargs)
        return response
    return inner

@ignore_warnings
def foo(arg1, arg2):
    ...
    write your code here without warnings
    ...

@ignore_warnings
def foo2(arg1, arg2, arg3):
    ...
    write your code here without warnings
    ...

すべての警告を無視する関数に@ignore_warningsデコレータを追加するだけです

3
Trideep Rath

それについてあなたをbeatるつもりはありませんが、あなたがやっていることは、あなたが次にPythonをアップグレードするとき、おそらく動作しなくなると警告されています。 intに変換して完了です。

ところで。独自の警告ハンドラを作成することもできます。何もしない関数を割り当てるだけです。 python警告をカスタムストリームにリダイレクトする方法

1
SpliFF

あなたが何をしているのかを知っている場合、別の方法は単に警告するファイルを見つけます(ファイルのパスは警告情報に表示されます)、警告を生成する行をコメントします

1
Statham

Dockerソリューション

  • pythonアプリケーションを実行する前に、すべての警告を無効にします
    • ドッキングされたテストも無効にすることができます
ENV PYTHONWARNINGS="ignore::DeprecationWarning"
1