[GRASS-user] Problems using qgis and grass in one python script

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

Hi,
I am not an expert of using GRASS from QGIS, so I don't know if there are mistakes in the first part where you call GRASS, but for what I can see could be a problem of empty output filename IMHO.

Il 13/09/2017 13:11, T K ha scritto:

...
all = ""
grass.script.run_command('v.import', input='/home/student/qgis/all.shp',
output=all)
...

Try to assign something to 'all' variable, for example:
all="test-out"
Otherwise you could use a little bit hardcoded approach setting directly the variable 'output' for v.import and the variable 'input' for v.to.rast:
v.import ... output='test-out'
...
v.to.rast ... input='test-out'

Best Regards,

Andrea Balotti

On 13/09/17 13:11, T K wrote:

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.

This is a good place, don't worry.

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.

You already received an answer about possible cause from Andrea.

However, this seems to be an awful lot of hoops to jump through for the task at hand. Why not just import your csv file directly into GRASS GIS with v.in.ascii ?

Moritz

On Fri, Sep 15, 2017 at 9:42 AM, Moritz Lennert <mlennert@club.worldonline.be> wrote:

On 13/09/17 13:11, T K wrote:

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.

This is a good place, don’t worry.

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.

You already received an answer about possible cause from Andrea.

However, this seems to be an awful lot of hoops to jump through for the task at hand. Why not just import your csv file directly into GRASS GIS with v.in.ascii ?

The last command is v.to.rast, therefore g.region + r.in.xyz with the csv file as input should do the job.

Markus M

Le 15 septembre 2017 10:01:15 GMT+02:00, Markus Metz <markus.metz.giswork@gmail.com> a écrit :

On Fri, Sep 15, 2017 at 9:42 AM, Moritz Lennert <
mlennert@club.worldonline.be> wrote:

On 13/09/17 13:11, T K wrote:

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.

This is a good place, don't worry.

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.

You already received an answer about possible cause from Andrea.

However, this seems to be an awful lot of hoops to jump through for

the
task at hand. Why not just import your csv file directly into GRASS GIS
with v.in.ascii ?

The last command is v.to.rast, therefore g.region + r.in.xyz with the
csv
file as input should do the job.

Right, even better if your only aim is to create a raster. It all depends on what you want to do further with the data.

Moritz