如何解析字符串看起来像 sys.argv [英] How to parse strings to look like sys.argv

查看:29
本文介绍了如何解析字符串看起来像 sys.argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析这样的字符串:

-o 1 --long "一些长字符串"

进入这个:

["-o", "1", "--long", '一些长字符串']

或类似的.

这与 getopt 或 optparse 不同,后者开始 sys.argv 解析输入(如我上面的输出).有没有标准的方法来做到这一点?基本上,这是拆分",同时将引用的字符串保持在一起.

迄今为止我最好的功能:

导入csvdef split_quote(string,quotechar='"'):'''>>>split_quote('--blah 这里有一些参数"')['--blah', '一些争论', '这里']>>>split_quote("--blah '这里有一些参数'", quotechar="'")['--blah', '一些争论', '这里']'''s = csv.StringIO(string)C = csv.reader(s, delimiter=" ",quotechar=quotechar)返回列表(C)[0]

解决方案

我相信您想要 shlex 模块.

<预><代码>>>>进口shlex>>>shlex.split('-o 1 --long "一些长字符串"')['-o', '1', '--long', '一些长字符串']

I would like to parse a string like this:

-o 1  --long "Some long string"  

into this:

["-o", "1", "--long", 'Some long string']

or similar.

This is different than either getopt, or optparse, which start with sys.argv parsed input (like the output I have above). Is there a standard way to do this? Basically, this is "splitting" while keeping quoted strings together.

My best function so far:

import csv
def split_quote(string,quotechar='"'):
    '''

    >>> split_quote('--blah "Some argument" here')
    ['--blah', 'Some argument', 'here']

    >>> split_quote("--blah 'Some argument' here", quotechar="'")
    ['--blah', 'Some argument', 'here']
    '''
    s = csv.StringIO(string)
    C = csv.reader(s, delimiter=" ",quotechar=quotechar)
    return list(C)[0]

解决方案

I believe you want the shlex module.

>>> import shlex
>>> shlex.split('-o 1 --long "Some long string"')
['-o', '1', '--long', 'Some long string']

这篇关于如何解析字符串看起来像 sys.argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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