{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 警告" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "出现了一些需要让用户知道的问题,但又不想停止程序,这时候我们可以使用警告:\n", "\n", "首先导入警告模块:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import warnings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在需要的地方,我们使用 `warnings` 中的 `warn` 函数:\n", "\n", " warn(msg, WarningType = UserWarning)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "c:\\Anaconda\\lib\\site-packages\\IPython\\kernel\\__main__.py:4: RuntimeWarning: month (13) is not between 1 and 12\n" ] } ], "source": [ "def month_warning(m):\n", " if not 1<= m <= 12:\n", " msg = \"month (%d) is not between 1 and 12\" % m\n", " warnings.warn(msg, RuntimeWarning)\n", "\n", "month_warning(13)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "有时候我们想要忽略特定类型的警告,可以使用 `warnings` 的 `filterwarnings` 函数:\n", "\n", " filterwarnings(action, category)\n", "\n", "将 `action` 设置为 `'ignore'` 便可以忽略特定类型的警告:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)\n", "\n", "month_warning(13)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }