从函数签名中内省的简单选项解析。
opterator的Python项目详细描述
opterator是一个用于python的选项解析脚本,它将模板取出 选项解析的。
opterator基于这样一种思想:脚本的main()函数可以是 修饰以允许将命令行参数转换为方法 参数。这使得它能够自我记录,并减少 创建和分配选项。我不知道你是否想把它用在大的 程序,但对于那些你不能 决定是否要使用argparse,但手动查询sys.argv是 有点太复杂了。
例如,您可以使用 像这样的操作者:
fromopteratorimportopterate@opteratedefmain(source,dest,backup=False,interactive=False):'''A script for renaming files :param source: the source file :param dest: the destination :param backup: backup the file :param interactive: -p --interactive interatively move files... '''# Move the fileif__name__=='__main__':main()
相比之下,optparse程序的可读性要差一些 代码行:
fromargparseimportArgumentParserdefmain():'''main entrypoint for renaming files. Accept two options, backup and interactive'''parser=ArgumentParser(usage="A script for renaming files")parser.add_argument("source",help="the source file")parser.add_argument("dest",help="the destination")parser.add_argument('-b','--backup',action="store_true",help='backup the file')parser.add_argument('-p','--interactive',action="store_true",help='interactively move files')arguments=parser.parse_args()# Move the fileif__name__=='__main__':main()
opterator自动从docstring生成帮助消息。主要 docstring的一部分成为帮助字符串的主要部分。个人 参数docStrings成为参数的帮助文本。默认情况下, 给定参数的长形式和短形式来自参数名和 参数名的第一个字符。在python 3中,可以用 函数注释;或者在Python2或3中,可以通过添加 在参数和 文档字符串。
所以,如果您的主要功能如下所示:
fromopteratorimportopterate@opteratedefmain(filename1,filename2,recursive=False,backup=False,suffix='~',*other_filenames):'''An example copy script with some example parameters that might be used in a file or directory copy command. :param recursive: -r --recursive copy directories recursively :param backup: -b --backup backup any files you copy over :param suffix: -S --suffix override the usual backup suffix '''filenames=[filename1,filename2]+list(other_filenames)destination=filenames.pop()print("You asked to move %s to %s"%(filenames,destination))ifrecursive:print("You asked to copy directories recursively.")ifbackup:print("You asked to backup any overwritten files.")print("You would use the suffix %s"%suffix)if__name__=='__main__':main()
您的帮助文本如下:
dusty:opterator $ python cp.py -h usage: cp.py [-h] [-r] [-b] [-S SUFFIX] filename1 filename2 [other_filenames [other_filenames ...]] An example copy script with some example parameters that might be used in a file or directory copy command. positional arguments: filename1 filename2 other_filenames optional arguments: -h, --help show this help message and exit -r, --recursive copy directories recursively -b, --backup backup any files you copy over -S SUFFIX, --suffix SUFFIX override the usual backup suffix
如果您想尝试使用时髦的函数注释语法,请给出 一个镜头:
fromopteratorimportopterate@opteratedefmain(show_details:['-l']=False,cols:['-w','--width']='',*files):''' List information about a particular file or set of files :param show_details: Whether to show detailed info about files :param cols: specify screen width '''print(files)print(show_details)print(cols)if__name__=='__main__':main()