3

QGIS 2.14 on Windows 7. I'm trying to call a method in a python script from the QGIS python console. I've put the directory in which the scripts resides in the PYTHONPATH in both the windows system and user environment variable.

The python script (first_script.py) has a method that looks like this:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface
def load_layer():
  wb = QgsVectorLayer('C:\Data\scripts\pyqbook\data\world_borders.shp', 'world_borders', 'ogr')
  QgsMapLayerRegistry.instance().addMapLayer(wb)

I call the script like this:

>>>import first_script
>>>first_script.load_layer()

and I get QGIS error: "Data source is invalid". However, when I then manually enter the two lines of the method, it works fine and loads the layer into the canvas correctly:

>>>wb = QgsVectorLayer('C:\Data\scripts\pyqbook\data\world_borders.shp', 'world_borders', 'ogr')
>>>QgsMapLayerRegistry.instance().addMapLayer(wb)

Why can't I call the method from the QGIS python console directly without getting the "Data source is invalid" error? The data source is valid because I can call the individual lines of the method and get the correct result.

6

The slashes are going the wrong way in the url directory path to the shp. Python interprets "\" as line return. Use "/" instead or "r" in front of the string path.

"C:/Data/scripts/...etc"

Or

r"C:\Data\scripts...etc"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.