2

I want to be able to take a string like below and pull out the first parameter (id) and then use that to print it out. I have been looking into split for python, but I usually have to split 2 or 3 times before getting something usable.

Here is an example of the strings I am trying to parse:

EntryError(u"(sqlite3.IntegrityError) UNIQUE constraint failed:
role.name, role.domain_id [SQL: u'INSERT INTO table1 (id, name, 
domain_id, extra) VALUES (?, ?, ?, ?)'] [parameters: ('id', 
'fake1name', '<<null>>', '{}')]",)

I have tries things like:

e = e.split("\'")
e = e.split(",")

But this gives me weird strings that have to further be parsed. Is there an easier way to always pull the id from "[parameters: ('id', 'fake1name', '<<null>>', '{}')]"?

Here's the code I have:

except exception.EntryError as e:   

    query = str(e)
    # example of me using split to try and reduce the string
    parsedstr = query.split("[")
    parsedstr = parsedstr.split("\'")

    # This will give me id like I want but it doesn't seem efficient
    # prints: id
    print parsedstr[1]
2
  • 2
    Could you show the rest of your code - do you actually have access to the cursor or the exception instance itself? Thanks. Commented Nov 30, 2016 at 21:17
  • What string are you trying to parse? Are you actually trying to parse the message in the EntryError object above? Commented Nov 30, 2016 at 21:25

1 Answer 1

1

You can use regular expressions.

import re

...

except exception.EntryError as e:
    print re.search("\[parameters: \('([^']+)", str(e)).group(1)

This would search the exception string for the first occurrence of [parameters: (' and start matching from that point until it hits a '.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.