1

I am relatively new to python and pycparser. I have already parsed the c file into an AST using the c-to-c.py file from https://github.com/eliben/pycparser. I am now trying to make a CFG using the AST but I am unable to store the information in .show() as a string. How do i go about storing this .show() information, i have tried to use test=ast.children()[0][1].show() however when i try to print test out it states "none". So is there another way of storing it? Or is there another method that i can use to read through the .show() information. Thank you.

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 Answers1

1

As you can see from its documentation string, show takes a buf parameter to which it will print the representation. By default it's sys.stdout but you can pass your own.

For full flexibility you can use StringIO - it will let you grab the output into a string.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412