I've been trying, along with this post, to run a script in OSGeo4w Shell, outside of QGIS. But I get the following error:
ImportError: No module named qgis.core
I have also read the following posts and tried to import various modules but to no avail:
- How to run sextante algorithms outside of QGIS python console?
- How to run a simple python script for QGIS from outside (e.g. Sublime Text)?
- Writing standalone Python scripts using PyQGIS?
Here is a simple script which creates a grid and clips a polygon shapefile onto it.
Note: This script has been tested and works successfully when running in QGIS.
##Test=name
import os
import glob
import sys
sys.path.append("C:\Program Files\QGIS Brighton\lib;%OSGEO4W_ROOT:\=/%/apps/qgis;%OSGEO4W_ROOT%\apps\qgis\bin;%OSGEO4W_ROOT%\apps\grass\grass-6.4.3\lib;%PATH%")
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
QgsApplication.setPrefixPath("C:\Program Files\QGIS Brighton\apps\qgis", True)
QgsApplication.initQgis()
from os.path import expanduser
home = expanduser("~")
# Folder path of the Results for shapefiles
path_dir = home + "\Desktop\Test\\"
path_res = path_dir + "Results\\"
def run():
# Set directory, search for all polygon .shp files and run the Create Grid and Clip algorithms then output results into Results folder
os.chdir(path_dir + "Shapefiles\\")
for fname in glob.glob("*.shp"):
outputs_1=processing.runalg("qgis:creategrid", 1000, 1000, 24108, 18351.157175, 258293.802316, 665638.226408, 1, 'EPSG:7405', None)
outputs_2=processing.runalg("qgis:clip", outputs_1['SAVENAME'], fname, path_res + "/"+ fname)
run()
QgsApplication.exitQgis()
# Remove the above line when running in QGIS
Following the answer and the script posted by @gcarrillo, I can finally import the qgis.core.
modules successfully. The script provided by @gcarrillo runs but I receive a Traceback error:
Traceback (most recent call last):
File "Test.py", line 55, in <module>
run()
File "Test.py", line 53, in run
algClip.processAlgorithm(progress)
File "C:\Users\username\.qgis2\python\plugins\processing\algs\qgis\ftools\Clip.py", line 59, in processAlgorithm
layerA.pendingFields(),
AttributeError: 'NoneType' object has no attribute 'pendingFields'