Python,如何将字符串解析为sys.argv [英] Python, how to parse strings to look like sys.argv
本文介绍了Python,如何将字符串解析为sys.argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想解析这样的字符串:
I would like to parse a string like this:
-o 1 --long "Some long string"
对此:
["-o", "1", "--long", 'Some long string']
或类似的
这与getopt或optparse不同,后者以sys.argv解析的输入(例如我上面的输出)以 start 开始.有没有标准的方法可以做到这一点?基本上,这是拆分",同时将引用的字符串保持在一起.
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]
推荐答案
我相信您想要 shlex 模块.
>>> import shlex
>>> shlex.split('-o 1 --long "Some long string"')
['-o', '1', '--long', 'Some long string']
这篇关于Python,如何将字符串解析为sys.argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文