5

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.

1
  • 1
    Have you tried to play it in the osgeo console? Commented May 7, 2018 at 21:22

1 Answer 1

6

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"

If you get this error: Fatal Python error: initfsencoding: unable to load the file system codec, run py3_env.bat in OSGeo Shell, then run the command above again.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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