编写命令行脚本从像您这样的简单需求开始(让我只输入一个文件名),很快就会导致更复杂的场景。在
这时,一些命令行参数解析器派上了用场。在
有许多选择,其中一些是:sys.argv:不是命令行解析器,在更复杂的情况下会很短
argparse:python2.7之后的stdlib的一部分,但是需要很多额外的代码
plac:实用程序脚本非常方便,除非您有更复杂的情况
docopt:到目前为止,我发现的处理命令行解析的最好、最干净的方法
使用docopt进行命令行分析
首次安装docopt:$ pip install docopt
然后写你的脚本readfile.py
^{pr2}$
到目前为止,我们为文件和要调用的函数编写了docstring。在
readfile.py续
但真正的解析会到来(它必须在同一个文件中,放在最后):if __name__ == "__main__":
from docopt import docopt
args = docopt(__doc__)
print "args", args
filenames = args[""]
caseconvert = "keep"
if args[" uppercase"]:
caseconvert = "upper"
if args[" lowercase"]:
caseconvert = "lower"
reverse = args[" reverse"]
print " - Converted file content: "
convertfunc = get_convert_func(caseconvert, reverse)
printfiles(filenames, convertfunc)
正在尝试代码
最后试试:$ python readfile.py
Usage:
readfile.py [( uppercase| lowercase| swapcase)] [ reverse] ...
readfile.py -h
尝试查看更多帮助:
$python读文件.py-h
读取文件(并可能转换行)
用法:
读文件.py[大写][小写]。。。
读文件.py-hOptions:
-U uppercase Convert text to uppercase
-L lowercase Convert text to lowercase
-S swapcase Swap character cases
-R reverse Reverse text on each line
Reads file(s) , optionally convert lines to uppercase or lowercase and
possibly reverses text of each line.
Output is printed to stdout.
做一些实际行动:$ python readfile.py -UR readfile.py ../th.py
args {' lowercase': False,
' reverse': True,
' swapcase': False,
' uppercase': True,
'-h': False,
'': ['readfile.py', '../th.py']}
- Converted file content:
)SENIL TREVNOC YLBISSOP DNA( ELIF DAER"""
:EGASU
...>EMANELIF< ]ESREVER [ ])ESACPAWS |ESACREWOL |ESACREPPU ([ YP.ELIFDAER
H- YP.ELIFDAER
:SNOITPO
ESACREPPU OT TXET TREVNOC ESACREPPU U-
ESACREWOL OT TXET TREVNOC ESACREWOL L-
SESAC RETCARAHC PAWS ESACPAWS S-
....etc....
最后的评论忽略执行实际操作的代码(这并不重要,但对于命令行解析则不重要)
脚本文件应具有正确格式的docstring-这是docopt命令行解析规则的源。这些规则必须学习,但它们不是那么困难,它们能够表达大量不同的组合。在
docopt(__doc__)正在解析所谓的docstring,它是从脚本文件initial"""(some strint..."""部分读取的。在
docopt解析的结果将打印在输出上,以显示从解析命令行获得的字典。在生产代码中,这将被删除。在
为了显示灵活性,这个示例变得更加复杂(只有在不计算docstring的情况下,请求一个文件名将花费我们2行代码)。最大的优点是,docopt将使docstring成为脚本的重要部分,这是非常可读(也是有效的)docstring。在