[GIS] Importing modules in PyQGIS

nameerrorpyqgis

I am trying to build a a library of scripts to call inside the QGis Python console/Python editior. I do not understand why they work independently, but not when being called from another script.
Example:

file c:\scripts\A.py

def create_copy(input,output): 
    layer = QgsVectorLayer(input, "input", "ogr")
    error = QgsVectorFileWriter.writeAsVectorFormat(layer, output, "utf-8", None, "ESRI Shapefile")

I can call that function, from within the same script:

create_copy(r"z:\original.shp", r"z:\copy.shp")

works as intended.

Now if I call this from another script, like so:

file c:\scripts\B.py

import sys
sys.path.insert(0, r'c:\scripts')
import A

A.create_copy(r"z:\original.shp", r"z:\copy.shp")

I get

NameError: global name 'QgsVectorLayer' is not defined.

Even though the call is made from within the QGis Python Editor. What am I missing?

Best Answer

Try replacing sys.path.insert(0, r'c:\scripts') with sys.path.append(r'c:\scripts') instead and add the required imports in your A.py.


c:\scripts\A.py

from qgis.core import QgsVectorLayer, QgsVectorFileWriter

def create_copy(input,output): 
    layer = QgsVectorLayer(input, "input", "ogr")
    error = QgsVectorFileWriter.writeAsVectorFormat(layer, output, "utf-8", None, "ESRI Shapefile")

c:\scripts\B.py

import sys
sys.path.append(r'c:\scripts')
import A

A.create_copy(r"z:\original.shp", r"z:\copy.shp")