LoginSignup
1
0

More than 1 year has passed since last update.

Python2 で Boto3 利用時に出力される PythonDeprecationWarning を抑制する

Last updated at Posted at 2022-06-05

Python2 で利用できる Boto3 の最終バージョン

Python で AWS を操作するライブラリとして Boto3 があります。
Boto3 を Python2 で利用する場合、最終バージョンは 1.17.112 になるようです。

1.18.0
...
feature:Python: Drop support for Python 2.7
feature:Python: [botocore] Dropped support for Python 2.7

1.18.0 の一つ前 が 1.17.112 になります。

警告 "PythonDeprecationWarning" が出力されてしまう

Python2 で Boto3 1.17.112 を利用してみるとエラーなく実行できますが、PythonDeprecationWarning という警告も出力されます。

import boto3 # v1.17.112

s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
    print(bucket.name)

# ./lib/boto3/compat.py:86: PythonDeprecationWarning: Boto3 will no longer support Python 2.7 starting July 15, 2021. To continue receiving service updates, bug fixes, and security updates please upgrade to Python 3.6 or later. More information can be found here: https://aws.amazon.com/blogs/developer/announcing-end-of-support-for-python-2-7-in-aws-sdk-for-python-and-aws-cli-v1/
#  warnings.warn(warning, PythonDeprecationWarning)
# bucket-1
# bucket-2
# ...

結果を見るだけなら警告は無視すればいいですが、別の処理に渡す場合は問題が生じそうです。
上の例では1〜2行目の警告文を削除してバケット名だけを渡すようにしないといけないでしょう。

PythonDeprecationWarning を抑制する

warnings モジュールの simplefilter() を使って PythonDeprecationWarning を出力させないようにします。

import boto3
+ import warnings

+ warnings.resetwarnings()
+ warnings.simplefilter('ignore', boto3.exceptions.PythonDeprecationWarning)

s3 = boto3.resource('s3')

for bucket in s3.buckets.all():
    print(bucket.name)

# bucket-1
# bucket-2
# ...

simplefilter() の第二引数に抑制したい警告のカテゴリ(クラス)を指定します。
PythonDeprecationWarning は Boto3 独自の警告のため定義されたクラスも含めて指定してください。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0