0

我对 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)
4

1 回答 1

0

从它的文档字符串中可以看出,它show接受一个buf参数,它将打印表示。默认情况下它是sys.stdout但你可以通过你自己的。

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

于 2017-04-07T12:02:08.297 回答