#!/usr/bin/python

import re
import subprocess


class SXPParser(object):
    tokenizer_rules = r""" (?P<open> \( ) | (?P<close> \) ) | (?P<whitespace> \s+ ) | [^()^\s]+ """
    tokenizer_re = re.compile(tokenizer_rules, re.X)

    def __init__(self):
        self.stack = []
        self.data = []

    def __call__(self, input):
        for match in self.tokenizer_re.finditer(input):
            if match.group('open'):
                self.stack.append([])
            elif match.group('close'):
                top = self.stack.pop()
                if self.stack:
                    self.stack[-1].append(top)
                else:
                    self.data.append(top)
            elif match.group('whitespace'):
                pass
            else:
                if self.stack:
                    self.stack[-1].append(match.group())
        return self.data


if __name__ == '__main__':
    p = subprocess.check_output(('xen', 'list', '-l'))
    s = SXPParser()(p)
    for i in s:
        if i and i[0] == 'domain':
            try:
                data = dict(j for j in i if len(j) == 2)
                domid = int(data['domid'])
                name = data['name']
                if domid == 0:
                    continue
                print domid, name
            except (KeyError, ValueError) as e:
                pass
