如何将任意选项字符串解析为python字典 [英] How to parse an arbitrary option string into a python dictionary

查看:109
本文介绍了如何将任意选项字符串解析为python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到最Pythonic的方式来获取包含命令行选项的字符串:

I am trying to find the most Pythonic way to take a string containing command line options:

"-t 500 -x -c 3 -d"

将其变成字典

{"-t":"500", "-x":True, "-c":"3", "-d": True}

更新:该字符串还应该能够包含--long选项以及中间带有破折号的单词:

UPDATE: The string should also be able to contain --long options, and words with dashes in the middle:

"-t 500 -x -c 3 -d --long-option 456 -testing weird-behaviour"

在建议我查看OptionParse模块之前,请记住我不知道有效选项是什么或类似的东西,我只是试图将字符串放入字典中,以允许基于其他字典对其进行修改选项.

Before suggesting that I look into OptionParse module, keep in mind I don't know what the valid options are or anything like that, I am just trying to put the string into a dictionary to allow modifying it based on a different dictionary of options.

我正在考虑的方法是使用split()将项目放入列表中,然后遍历列表并查找以破折号-"开头的项目并将其用作键,然后以某种方式进入值中列表中的下一项.我遇到的问题是没有值的选项.我想到了做类似的事情:

The approach I am considering is using split() to get the items into a list and then walking the list and looking for items that begin with a dash "-" and use them as the key, and then somehow getting to the next item on the list for the value. The problem I have is with options that don't have values. I thought of doing something like:

for i in range(0, len(opt_list)):
        if opt_list[i][0] == "-":
            if len(opt_list) > i+1 and not opt_list[i+1][0] == "-":
                opt_dict[opt_list[i]] = opt_list[i+1] 
            else:
                opt_dict[opt_list[i]] = True

但是当我这样做时,似乎我正在用C而不是Python进行编程...

But it seems like I am programming in C not Python when I do that...

推荐答案

要正确处理引号内的空格,您可以使用

To handle spaces inside quotes correctly you could use shlex.split():

import shlex

cmdln_args = ('-t 500 -x -c 3 -d --long-option 456 '
              '-testing "weird -behaviour" -m "--inside"')

args = shlex.split(cmdln_args)
options = {k: True if v.startswith('-') else v
           for k,v in zip(args, args[1:]+["--"]) if k.startswith('-')}

from pprint import pprint
pprint(options)

输出

{'--inside': True,
 '--long-option': '456',
 '-c': '3',
 '-d': True,
 '-m': True,
 '-t': '500',
 '-testing': 'weird -behaviour',
 '-x': True}

这篇关于如何将任意选项字符串解析为python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆