What if I would like to have the full SpatiaLite database path from a vector layer loaded in the TOC with PyQGIS?
With a very simple example, by storing active vector layer in a variable:
vl = iface.activeLayer()
one can retrieve the providerType
and the dataSourceUri
:
vl.providerType()
u'spatialite'
vl.dataProvider().dataSourceUri()
vl.dataProvider().dataSourceUri()
u'dbname=\'/home/matteo/myDataBase.sqlite\' table="river_layer" (geometry) sql='
Is there a simple method to get as a string, just the path of the database (so. /home/matteo/myDataBase.sqlite)?
-
1Thanks Joseph! Do you think (or know) if the method you suggest is also cross-platform? Great pythonic way to solve the problem ;)matteo– matteo2017年06月14日 13:53:09 +00:00Commented Jun 14, 2017 at 13:53
-
Most welcome! Hmm I can't tell you for sure, I tested this on a Windows machine so if it works for you too then that's two platforms down ;)Joseph– Joseph2017年06月14日 13:56:46 +00:00Commented Jun 14, 2017 at 13:56
-
1ehehe.. 2 down is good.. Thanks Joseph, if want you can copy and paste your comment as a question so I will accept it. Thanks again!matteo– matteo2017年06月14日 14:08:40 +00:00Commented Jun 14, 2017 at 14:08
1 Answer 1
Similar to this question but if you only want to extract the path of the dataSourceUri()
(and not u'dbname=\'/home/matteo/myDataBase.sqlite\'
), you could use:
vl.dataProvider().dataSourceUri().split(' ')[0].replace('dbname=','').replace("'","")
Which should give:
u'/home/matteo/myDataBase.sqlite'
-
1Question about that: Why don't you use
vl.source()
instead ofvl.dataProvider().dataSourceUri()
?YoLecomte– YoLecomte2017年06月14日 14:56:06 +00:00Commented Jun 14, 2017 at 14:56 -
@YoLecomte - You're correct in that you could use
vl.source()
to extract the uri path which could shorten it tovl.source().split(' ')[0].replace('dbname=','').replace("'","")
. But typically when using Spatialite (or PostGIS) databases, you usevl.dataProvider().dataSourceUri()
to not only extract the uri information but also set up the connection parameters. I guess in the end, it's just personal preference :)Joseph– Joseph2017年06月14日 15:05:11 +00:00Commented Jun 14, 2017 at 15:05 -
@YoLecomte - Most welcome =)Joseph– Joseph2017年06月14日 15:10:17 +00:00Commented Jun 14, 2017 at 15:10