Sam*_*Sam 26 python command-line command-line-arguments command-line-parsing
我想在提供一些参数的时候从命令行运行我的python脚本.但是,其中一个参数应该是特定于脚本的一个段的选项列表.在从逗号分割"命令行列表"字符串后,通过实际构建列表,字符串解析是唯一的方法吗?如果是这样,你会怎么做?
示例:-details = ['name','title','address']
the*_*olf 28
程序:
import sys, ast, getopt, types
def 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:])
Run Code Online (Sandbox Code Playgroud)
命令行:
python py.py --l='[1,2,3,[1,2,3]]' -d "{1:'one',2:'two',3:'three'}" --tu='(1,2,3)'
Run Code Online (Sandbox Code Playgroud)
输出:
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'>
Run Code Online (Sandbox Code Playgroud)
这段代码片段将采用短或长命令开关,-l或者--li=在切换到像list,tuple或dict这样的Python数据结构后解析文本.解析的数据结构最终在具有长格式切换键的字典中.
使用ast.literal_eval是相对安全的.它只能解析python数据定义.
Tho*_*mas 26
argparse很不错,它在2.7和3.2的标准库中,但在其他方面pip install.
您可以通过使用引号将列表解释为shell中的单个参数来解决您指定可变长度列表的主要问题(我可能依赖于您的shell):
% python prog.py 'name title address' spam
Run Code Online (Sandbox Code Playgroud)
prog.py包含的地方
import sys
my_list = sys.argv[1].split()
# my_list is ['name', 'title', 'address']
if 'name' in my_list:
do_something()
Run Code Online (Sandbox Code Playgroud)
或类似的.使用带分割的参数来分隔列表:
% python prog.py "you're a foo, lift the bar"
my_list = [x.strip() for x in sys.argv[1].split(',')]
# my_list is ["you're a foo", "lift the bar"]
Run Code Online (Sandbox Code Playgroud)
但请改用argparse; 特别是如果你想使用使用-c样式标志.
解释您的问题的一种方法是:
"我已经在使用argparse,因为这是解释Python中命令行参数的明智方法.我如何指定某些选项在特定类别中?"
在你的问题中,你已经展示了我使用的外壳会阻塞的一些例子;
% python prog.py -v -details=['name', 'title', 'address'] --quickly -t 4
Run Code Online (Sandbox Code Playgroud)
不会让python被解析,因为他们使用空格来分隔参数,并可能使用[和]作为shell语法.
我建议以下内容
% python prog.py -v --details name title address --quickly -t 4
Run Code Online (Sandbox Code Playgroud)
其中的prog.py文件
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', action='store_true')
parser.add_argument('--details', nargs='*')
parser.add_argument('--quickly', action='store_true')
parser.add_argument('-t')
args = parser.parse_args()
#args is Namespace(details=['asdf', 'a', 'a'], quickly=False, t='4', v=True)
details = args.details
#details is ['asdf', 'a', 'a']
Run Code Online (Sandbox Code Playgroud)
现在,根据您的问题,您不必自己进行字符串解析.
| 归档时间: |
|
| 查看次数: |
51167 次 |
| 最近记录: |