2017-04-07 85 views
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()信息。謝謝。如何存儲AST兒童信息(python)

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) 

回答

0

正如你可以從它的文檔字符串看,show需要buf參數,它將打印表示。默認情況下它是sys.stdout,但你可以傳遞你自己的。

要獲得充分的靈活性,您可以使用StringIO - 它可以讓您將輸出抓取到字符串中。