Pyparsing: getting the results of the analyzed data

I am trying to parse multiple statements SQL(for CREATE TABLEsure) using pyparsing. For the database name and table table, I created identifiers:

identifier = (Combine(Optional('"') + Word(alphanums) + 
                      ZeroOrMore('_' + Word(alphanums)) + 
                      Optional('"')) & ~keywords_set)

database_name = identifier.setResultsName('database_name')
table_name = identifier.setResultsName('table_name')

I also use this parsing method:

def parse(self, sql):
    try:
        tokens = self.create_table_stmt.parseString(sql)
        print tokens.database_name, tokens.table_name
        values = tokens.database_name, tokens.table_name
        print values
        return values
    except ParseException as error:
        print error

For the following input:

    CreateTableParser().parse('''
CREATE TABLE "django"."django_site1" (
)''')

I get:

['"django"'] ['"django_site1"']
((['"django"'], {}), (['"django_site1"'], {}))

Why are they different? How can I just get the output in the first place, like simple lists? I only get it when printing these values.

+3
source share
1 answer

There is a difference between print a, band print (a,b):

>>> a, b = "ab"
>>> a
'a'
>>> b
'b'
>>> print a, b
a b
>>> print (a, b)
('a', 'b')

print a, bprints two objects aand b. print (a, b)prints one tuple object a, b:

>>> w = sys.stdout.write
>>> _ = w(str(a)), w(' '), w(str(b)), w('\n')
a b
>>> _ = w(str((a,b))), w('\n')
('a', 'b')

Or else:

>>> class A:
...    def __str__(self):
...        return '1'
...    def __repr__(self):
...        return 'A()'
... 
>>> print A(), A()
1 1
>>> print (A(), A())
(A(), A())

__str__ , str(obj). __str__ , __repr__ repr(obj).

+1

Source: https://habr.com/ru/post/1781985/


All Articles