]> git.phdru.name Git - sqlconvert.git/blob - mysql2sql/print_tokens.py
Output tokens to an output stream instead of printing
[sqlconvert.git] / mysql2sql / print_tokens.py
1
2 import sys
3 try:
4     from cStringIO import StringIO
5 except ImportError:
6     try:
7         from StringIO import StringIO
8     except ImportError:
9         from io import StringIO
10 from sqlparse.sql import TokenList
11
12
13 def print_subtree(token_list, outfile=sys.stdout, ident=0):
14     for token in token_list:
15         outfile.write(" "*ident)
16         outfile.write(repr(token))
17         outfile.write("\n")
18         if isinstance(token, TokenList):
19             print_subtree(token, outfile, ident+4)
20
21
22 def print_tokens(token_list, outfile=sys.stdout, level=0):
23     for token in token_list:
24         if not isinstance(token, TokenList):
25             outfile.write(token.normalized)
26         if isinstance(token, TokenList):
27             print_tokens(token, outfile, level+1)
28     if level == 0:
29         outfile.write(';\n')
30
31
32 def get_tokens_str(token_list):
33     sio = StringIO()
34     print_tokens(token_list, outfile=sio)
35     return sio.getvalue()