alsamixer amixer to python dictionary格式

时间:2015-08-11 07:50:54

标签: python dictionary file-io

alsamixer将其数据存储在一个文件中,语法如下:

control.2 = {
    iface : MIXER
    name : 'DSP1 Rate'
    value:'16kHz'
    comment = {
        access 'read write'
        type ENUMERATED
        count 1
        item.0 'SYNCCLK rate'
        item.1 '8kHz'
        item.2 '16kHz'
        item.3 'ASYNCCLK rate'
    }

有没有速度方法将其转换为python字典? 允许从python脚本中读取它吗?

我已尝试 pyalsaaudio alsaaudio.mixers()可以看到控件的名称,但是使用alsa文件,您还可以看到可以设置的可用数据对于那种控制。

1 个答案:

答案 0 :(得分:3)

我整个下午都在这样做。希望它能解决你的问题:

#!/usr/bin/env python2.7
import re
import json


def jsonify(config='/var/lib/alsa/asound.state'):
    g = re.MULTILINE
    p1 = re.compile(r'((?:^|"[^"]+"|\'[^\']+\'|[\s:{}])+)([^\s{}]+)', g)
    p2 = re.compile(r'^(\s*\"[\w.]+"(?!\s*[\:]))', g)
    p3 = re.compile(r'([\"\}])\n(?!\s*\})', g)

    with open(config) as fh:
        context = fh.read()
        # replace all the quote with quotes
        context = context.replace("'", '"')
        # surround the name:value objects by quotes
        context = re.sub(p1, r'\g<1>"\g<2>"', context)
        # add a trailing comma after the values assignment
        context = re.sub(p2, r'\g<1>:', context)
        # add a colon before the values as a delimiter
        context = re.sub(p3, r'\g<1>,\n', context)

    return json.loads('{\n%s\n}' % context[:-2])


if __name__ == '__main__':
    print 'you should use it as module :D'