[GRASS-user] Problems using qgis and grass in one python script
T K
trikni at outlook.com
Wed Sep 13 04:11:36 PDT 2017
Hello list,
I am very new to the whole GIS topic, so I do not know if this is the
right place for my question, but I did not find a more suitable place.
I am trying to combine QGIS and GRASS in one python script.
The first step is to import a csv-file and create a shp-layer with QGIS
which runs without errors. But when I try to load the shp with grass
run_command like v.import or v.in.ogr there is always an error Illegal
filename. Character < > are not allowed. I am facing this problem for a
few days now and do not know how to solve it on my own. Here are some
snippets of my code:
import os, sys
import subprocess
from PyQt4.QtCore import QUrl, QString, QVariant
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry,
QgsApplication, QgsVectorFileWriter
# GRASS
grass7bin = 'grass72'
gisdb = os.path.join(os.path.expanduser("~"), "grassdata")
startcmd = [grass7bin, '--config', 'path']
try:
p = subprocess.Popen(startcmd, shell=False, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
except OSError as error:
sys.exit("ERROR: Cannot find GRASS GIS start script"
" {cmd}: {error}".format(cmd=startcmd[0], error=error))
if p.returncode != 0:
sys.exit("ERROR: Issues running GRASS GIS start script"
" {cmd}: {error}"
.format(cmd=' '.join(startcmd), error=err))
gisbase = out.strip(os.linesep)
location = "data"
mapset = "PERMANENT"
# set GISBASE environment variable
os.environ['GISBASE'] = gisbase
# define GRASS-Python environment
grass_pydir = os.path.join(gisbase, "etc", "python")
sys.path.append(grass_pydir)
#sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "python"))
import grass.script
import grass.script.setup
rcfile = grass.script.setup.init(gisbase, gisdb, location, mapset)
QgsApplication.setPrefixPath("/home/student/qgis", True)
qgs = QgsApplication([], True)
qgs.initQgis()
print(str(QgsApplication.showSettings()))
# Define the data source
filename="/home/student/qgis/v1/all.csv"
uri=QUrl.fromLocalFile(filename)
uri.addQueryItem("type","csv")
uri.addQueryItem("delimiter",";")
uri.addQueryItem("useHeader","yes")
uri.addQueryItem("encoding", "utf-8")
uri.addQueryItem("decimalPoint", ".")
uri.addQueryItem("xField", "X")
uri.addQueryItem("yField", "Y")
uri.addQueryItem("crs", "EPSG:25832")
uri.addQueryItem("geomType", "point")
layer=QgsVectorLayer(QString(uri.toEncoded()),"TestCSVlayer","delimitedtext")
# Add the layer to the map
if layer.isValid():
print("Valid layer")
QgsMapLayerRegistry.instance().addMapLayer(layer)
else:
print("Invalid layer")
features = layer.getFeatures()
for feature in features:
attrs = feature.attributes()
vector_writer_status = QgsVectorFileWriter.writeAsVectorFormat(layer,
"all.shp", "CP1250", None, "ESRI Shapefile")
if vector_writer_status == QgsVectorFileWriter.NoError:
print("Vector successfully written")
else:
print("Error while vector writing")
all = ""
grass.script.run_command('v.import', input='/home/student/qgis/all.shp',
output=all)
output_for_v_to_rast = 'output_from_v_to_rast'
column_name = 'ELEV'
grass.script.run_command('v.to.rast', input=all,
output=output_for_v_to_rast, attribute_column=column_name, type='point',
use='attr', value=10)
The error appears while at the v.import command and the script exits.
Inside the QGIS with GRASS GUI it runs all as expected but unfortunately
the proccess window is closing after finishing and the commands are not
readable and I would like to automate it.
I hope my problem is understandable.
Best regards
More information about the grass-user
mailing list