我认为 perl 更适合这种动态脚本。如果您想要快速运行一次性脚本功能,我建议您坚持使用 perl、awk、sed 和标准 unix 命令行工具。
但是如果你对使用 python 感兴趣,我使用optparse编写我自己的命令行工具并推荐它。optparse 提供了一个干净且易于使用的命令行选项解析器,内置帮助生成。
这是一个示例:
def myfunc(filename, use_versbose):
# function code
if __name__ == '__main__':
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()
if options.filename:
myfunc(options.filename, options.verbose)
else:
print 'ERROR -- Necessary command line options not given!'
print parser.print_help()
parser.print_help() 生成以下输出,并在命令行中给出 -h 或 --help 时自动显示:
usage: <yourscript> [options]
options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to stdout