2

I'm trying to use v.generalize in the GRASS GIS library within a python code in PyCharm on my Linux Ubuntu system to make a shapefile that originally was a raster look less "blocky" by simplifying its geometries.

I installed grass and grass.script via the terminal in PyCharm by running pip install grass and pip install grass.script. However, when I try to import grass.script into my code and run it, I get the error: "No module named grass.script."

How do I get grass to work within PyCharm? My code is below.

import glob
import os
import subprocess
import geopandas
import grass.script as grass

file_path = input('Enter file path to the folder containing your categorized tifs: ')
while not os.path.isdir(file_path):
    file_path = input("\nThe path you have entered does not exist. Please try again: ")

mask = input("Input shp to use as mask: ")
while not os.path.isfile(mask):
    mask = input("\nThe file you have entered does not exist. Please try again: ")

mask = geopandas.read_file(mask)

for f in glob.glob(file_path + "*.tif"):  
    out_file = f[:-4] + ".shp"
    in_file = os.path.join(file_path, f) 
    cmdline = ['gdal_polygonize.py', in_file, out_file]
    subprocess.call(cmdline)
    out_file = geopandas.read_file(out_file)
    clipped = geopandas.clip(out_file, mask)
    # clipped.to_file(f[:-4] + '_clipped.shp')
    generalized_out = (f[:-4] + "_generalized.shp")
    cmdline2 = grass.run_command('v.generalize', input=clipped, method='chaiken', threshold=0.1, output=generalized_out)
    subprocess.call(cmdline2)

EDITED:

So I looked at the grass wiki page and it says I need to run the following code, but am not sure what to put for the location and mapset. Any ideas?

import os
import sys
import subprocess

# path to the GRASS GIS launch script
# MS Windows
grass7bin_win = r'C:\OSGeo4W\bin\grass78dev.bat'
# uncomment when using standalone WinGRASS installer
# grass7bin_win = r'C:\Program Files (x86)\GRASS GIS 7.8.0\grass78.bat'
# Linux
grass7bin_lin = 'grass78'
# Mac OS X
# this is TODO
grass7bin_mac = '/Applications/GRASS/GRASS-7.8.app/'

# DATA
# define GRASS DATABASE
# add your path to grassdata (GRASS GIS database) directory
gisdb = os.path.join(os.path.expanduser("~"), "grassdata")
# the following path is the default path on MS Windows
# gisdb = os.path.join(os.path.expanduser("~"), "Documents/grassdata")

# specify (existing) location and mapset
location = "nc_spm_08"
mapset   = "user1"


########### SOFTWARE
if sys.platform.startswith('linux'):
    # we assume that the GRASS GIS start script is available and in the PATH
    # query GRASS 7 itself for its GISBASE
    grass7bin = grass7bin_lin
elif sys.platform.startswith('win'):
    grass7bin = grass7bin_win
else:
    raise OSError('Platform not configured.')

# query GRASS 7 itself for its GISBASE
startcmd = [grass7bin, '--config', 'path']

p = subprocess.Popen(startcmd, shell=False,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
    print >>sys.stderr, "ERROR: Cannot find GRASS GIS 7 start script (%s)" % startcmd
    sys.exit(-1)
gisbase = out.strip('\n\r')

# Set GISBASE environment variable
os.environ['GISBASE'] = gisbase
# the following not needed with trunk
os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'extrabin')
# add path to GRASS addons
home = os.path.expanduser("~")
os.environ['PATH'] += os.pathsep + os.path.join(home, '.grass7', 'addons', 'scripts')

# define GRASS-Python environment
gpydir = os.path.join(gisbase, "etc", "python")
sys.path.append(gpydir)

########### DATA
# Set GISDBASE environment variable
os.environ['GISDBASE'] = gisdb
 
# import GRASS Python bindings (see also pygrass)
import grass.script as gscript
import grass.script.setup as gsetup
 
###########
# launch session
gsetup.init(gisbase,
            gisdb, location, mapset)
 
gscript.message('Current GRASS GIS 7 environment:')
print gscript.gisenv()
 
gscript.message('Available raster maps:')
for rast in gscript.list_strings(type = 'rast'):
    print rast
 
gscript.message('Available vector maps:')
for vect in gscript.list_strings(type = 'vect'):
    print vect

1 Answer 1

0

I think that it's no enough to install and import the GRASS python modules. You need to do the initialization of a GRASS session as described in this wiki page

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.