Skip to main content
1 of 3
user2031
  • 231
  • 3
  • 13

How to fix "No module named grass.script in Linux PyCharm"?

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)
user2031
  • 231
  • 3
  • 13