Parse a DSN string in Python

A simple hack to get the different parts of a DSN string (which are used in PDO in PHP):

def parse_dsn(dsn):
    m ="([a-zA-Z0-9]+):(.*)", dsn)
    values = {}
    if (m and and
        values['driver'] =
        m_options = re.findall("([a-zA-Z0-9]+)=([a-zA-Z0-9]+)",
        for pair in m_options:
            values[pair[0]] = pair[1]

    return values

The returned dictionary contains one entry for each of the entries in the DSN.

Update: helge also submitted a simplified version of the above:

driver, rest = dsn.split(':', 1)
values = dict(re.findall('(\w+)=(\w+)', rest), driver=driver)

2 thoughts on “Parse a DSN string in Python”

  1. Hi! Can i really use your images on the rabbits on to a site which is called
    Btw, Im from sweden so I am not a expert on english.

    Sincerley Julia

Leave a Reply
