Python模块学习——使用 optparse 处理命令行参数
<div style="margin: 15px;">Python 有两个内建的模块用于处理命令行参数:
一个是 getopt,《Deep in python》一书中也有提到,只能简单处理命令行参数;
另一个是 optparse,它功能强大,而且易于使用,可以方便地生成标准的、符合Unix/Posix 规范的命令行说明。
<div class="section">示例
下面是一个使用 optparse 的简单示例:
from optparse import OptionParser[...]parser = OptionParser()parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE")parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout")(options, args) = parser.parse_args() 现在,妳就可以在命令行下输入:
<yourscript> --file=outfile -q<yourscript> -f outfile --quiet<yourscript> --quiet --file outfile<yourscript> -q -foutfile<yourscript> -qfoutfile 上面这些命令是相同效果的。除此之外, optparse 还为我们自动生成命令行的帮助信息:
<yourscript> -h<yourscript> --help 输出:
usage: <yourscript> options:-h, --help show this help message and exit-f FILE, --file=FILEwrite report to FILE-q, --quiet don't print status messages to stdout
页:
[1]