将包含json w/spaces的字符串拆分为参数

2024-04-20 07:44:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用cmd2实现一个命令shell,我想设置一些命令,允许用户以json语法键入对象。我原以为使用argparse可以很容易地完成这项工作,但是我现在正在学习如何解析字符串并将其呈现给argparse。我也愿意使用另一个模块。在

我一直在尝试使用regex来提取json,但是我没有看到一个简单的方法。在

首先,下面是一个使用命令行实用程序的示例:

import argparse
import json
import re

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--filter', type=json.loads)
    parser.add_argument('-n', '--name', type=str)

    args = parser.parse_args()
    print(args)

输出:

^{pr2}$

然后使用cmd2:

^{3}$

输出:

['example', '-n devices -f {"comment":"foobar"}']
- args: '-n devices -f {"comment":"foobar"}'
- command: 'example'
- raw: 'example -n devices -f {"comment":"foobar"}'
- statement: ['example', '-n devices -f {"comment":"foobar"}']
  - args: '-n devices -f {"comment":"foobar"}'
  - command: 'example'

Namespace(filter={u'comment': u'foobar'}, name='devices')
['example', '-n devices -f {"comment":"foo space bar"}']
- args: '-n devices -f {"comment":"foo space bar"}'
- command: 'example'
- raw: 'example -n devices -f {"comment":"foo space bar"}'
- statement: ['example', '-n devices -f {"comment":"foo space bar"}']
  - args: '-n devices -f {"comment":"foo space bar"}'
  - command: 'example'

usage: testparse2.py [-h] [-f FILTER] [-n NAME]
testparse2.py: error: argument -f/--filter: invalid loads value: '{"comment":"foo'

Tags: nameimportjsonparserfooexamplecommentargparse