我试图手动解析给定字符串的参数和标志.
例如,如果我有一个字符串
"--flag1 'this is the argument'"
我期待着回来
['--flag1', 'this is the argument']
对于字符串中任意数量的标志.
我遇到的困难是确定如何处理多字标志参数.
例如,如果我这样做(parser来自argparse)
parser.parse_args("--flag1 'this is the argument'".split())
"--flag1 'this is the argument'".split()"
变
['--flag1', "'this", 'is', 'the', "argument'"]
这不是我的期望.有一个简单的方法吗?
你很幸运; 有是一个简单的方法来做到这一点.使用shlex.split.它应该根据需要拆分字符串.
>>> import shlex
>>> shlex.split("--flag1 'this is the argument'")
['--flag1', 'this is the argument']
Run Code Online (Sandbox Code Playgroud)