如何存储AST儿童信息(python)

时间:2017-04-07 03:17:16

标签: python abstract-syntax-tree pycparser

我对python和pycparser比较新。我已经使用https://github.com/eliben/pycparser中的c-to-c.py文件将c文件解析为AST。我现在正在尝试使用AST制作CFG,但我无法将信息存储在.show()中作为字符串。我如何存储此.show()信息,我尝试使用test=ast.children()[0][1].show()但是当我尝试打印test时,它表示“无”。那还有另一种存储方式吗?或者是否有另一种方法可以用来读取.show()信息。谢谢。

def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showcoord=False, _my_node_name=None):
        """ Pretty print the Node and all its attributes and
            children (recursively) to a buffer.

            buf:
                Open IO buffer into which the Node is printed.

            offset:
                Initial offset (amount of leading spaces)

            attrnames:
                True if you want to see the attribute names in
                name=value pairs. False to only see the values.

            nodenames:
                True if you want to see the actual node names
                within their parents.

            showcoord:
                Do you want the coordinates of each Node to be
                displayed.
        """
        lead = ' ' * offset
        if nodenames and _my_node_name is not None:
            buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ')
        else:
            buf.write(lead + self.__class__.__name__+ ': ')

        if self.attr_names:
            if attrnames:
                nvlist = [(n, getattr(self,n)) for n in self.attr_names]
                attrstr = ', '.join('%s=%s' % nv for nv in nvlist)
            else:
                vlist = [getattr(self, n) for n in self.attr_names]
                attrstr = ', '.join('%s' % v for v in vlist)
            buf.write(attrstr)

        if showcoord:
            buf.write(' (at %s)' % self.coord)
        buf.write('\n')

        for (child_name, child) in self.children():
            child.show(
                buf,
                offset=offset + 2,
                attrnames=attrnames,
                nodenames=nodenames,
                showcoord=showcoord,
                _my_node_name=child_name)

1 个答案:

答案 0 :(得分:0)

从文档字符串中可以看出,show采用buf参数来打印表示。默认情况下它是sys.stdout但您可以通过自己的。

为了获得完全的灵活性,您可以使用StringIO - 它可以让您将输出抓取到字符串中。