2

I made a small script to save a shapefile to disk. I want to run the script through console. When I run the script through QGIS IDE, it runs successfully. But when I run it through the QGIS Python command prompt it says layer failed to load successfully.

What am I doing wrong?

from qgis.core import *
import qgis.utils


_layer = QgsVectorLayer("C:/Arundhati/RadioSignal/MasterLine.shp", "MASTERLINE", "ogr")

if not _layer.isValid():
  print("Layer failed to load!")    
else:
    print("Layer was loaded successfully!")

_writer = QgsVectorFileWriter.writeAsVectorFormat(_layer,                                
                               "C:/Arundhati/RadioSignal/MasterLine12.shp",
                               'utf-8',
                               QgsCoordinateReferenceSystem(),
                               'ESRI Shapefile')

I run the above file through QGIS Python console like the following:

enter image description here

Additionally Python also crashes:

enter image description here

What Am I doing wrong?

How to run the same script from outside the QGIS environment.

  • Have you tried to play it in the osgeo console? – Oscar Campo May 7 '18 at 21:22
3

First of all, you should review Using PyQGIS in standalone scripts for further information.

Also, try to run "OSGeo Shell" as @Oscar states.

enter image description here

According to the documentation, you need to change your code into (like) that:

from qgis.core import *

QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.0", True)  ###

qgs = QgsApplication([], False) ###
qgs.initQgis() ###

_layer = QgsVectorLayer("C:/Arundhati/RadioSignal/MasterLine.shp", "MASTERLINE", "ogr")

if _layer.isValid(): print("Layer was loaded successfully!")
else:  print("Layer failed to load!")

_writer = QgsVectorFileWriter.writeAsVectorFormat(_layer,
                                                  "C:/Arundhati/RadioSignal/MasterLine12.shp",
                                                  'utf-8',
                                                  _layer.sourceCrs(),
                                                  'ESRI Shapefile')

qgs.exitQgis() ###

and run the script in OSGeo Shell:

C:\Program Files\QGIS 3.0\bin> python3.exe "C:\Arundhati\RadioSignal\QGIS_test.py"

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.