栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从命令行将列表传递给Python

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从命令行将列表传递给Python

程序:

import sys, ast, getopt, typesdef main(argv):     arg_dict={}    switches={'li':list,'di':dict,'tu':tuple}    singles=''.join([x[0]+':' for x in switches])    long_form=[x+'=' for x in switches]    d={x[0]+':':'--'+x for x in switches}    try:         opts, args = getopt.getopt(argv, singles, long_form)    except getopt.GetoptError:       print "bad arg"         sys.exit(2)    for opt, arg in opts:     if opt[1]+':' in d: o=d[opt[1]+':'][2:]        elif opt in d.values(): o=opt[2:]        else: o =''        print opt, arg,o        if o and arg: arg_dict[o]=ast.literal_eval(arg)        if not o or not isinstance(arg_dict[o], switches[o]):     print opt, arg, " Error: bad arg" sys.exit(2)    for e in arg_dict:        print e, arg_dict[e], type(arg_dict[e])if __name__ == '__main__':    main(sys.argv[1:])

命令行:

python py.py --l='[1,2,3,[1,2,3]]' -d "{1:'one',2:'two',3:'three'}" --tu='(1,2,3)'

输出:

args:  ['--l=[1,2,3,[1,2,3]]', '-d', "{1:'one',2:'two',3:'three'}", '--tu=(1,2,3)']tu (1, 2, 3) <type 'tuple'>di {1: 'one', 2: 'two', 3: 'three'} <type 'dict'>li [1, 2, 3, [1, 2, 3]] <type 'list'>

此代码段将执行短或长命令切换(例如

-l
或),
--li=
并在切换到Python数据结构(如列表,元组或字典)后解析文本。解析的数据结构最终以带有长格式切换键的字典结尾。

使用ast.literal_eval相对安全。它只能解析python数据定义。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/638022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号