def qgis_init(verbose=False): ''' qgis_init() - Initialize the QGIS application Parameters ---------- verbose : bool, default=False True = command-line output on Returns ------- qgs : QGIS instance object ''' import qgis.core as qcore import init_qgis_paths as init_qgis_paths if verbose: print(' Initializing QGIS') app_path = init_qgis_paths() qcore.QgsApplication.setPrefixPath(app_path, True) # Path to QGIS binary # Create a reference to the QgsApplication, True = enables GUI (for applications) qgs = qcore.QgsApplication([], True) qgs.initQgis() # load providers if verbose: print(' QGIS Initialized') return qgs
def make_qgis_project_file(path): """Create a QGIS project file with the correct stuff in it. path: the desired path to .qgs project file, e.g.: /luigi/data/qgreenland/qgreenland.qgs Developed from examples: https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html#using-pyqgis-in-standalone-scripts """ # The qgis prefix path is two directories above the qgis executable. # See: # https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/intro.html#using-pyqgis-in-standalone-scripts qgis_path = subprocess.run( ['which', 'qgis'], stdout=subprocess.PIPE).stdout.decode('utf-8').strip('\n') qgis_prefix_path = os.path.abspath(os.path.join(qgis_path, '..', '..')) # Boilerplate QGIS initialization code; # - Suppresses "Application path not intialized" errors # - Enables Qt support for fonts used in layer styles (labels) qgs = qgc.QgsApplication([], False) qgs.initQgis() qgc.QgsApplication.setPrefixPath(qgis_prefix_path, True) # Create a new project; initializes basic structure project = qgc.QgsProject.instance() project.write(path) project_crs = qgc.QgsCoordinateReferenceSystem(CONFIG['project']['crs']) project.setCrs(project_crs) # Set the default extent. Eventually we may want to pull the extent directly # from the configured 'map frame' layer. view = project.viewSettings() background_extent = CONFIG['project']['extents']['data'] extent = qgc.QgsReferencedRectangle( qgc.QgsRectangle(*background_extent.values()), project_crs) view.setDefaultViewExtent(extent) _add_layers(project) _add_decorations(project) _set_groups_options(project) _add_empty_groups(project) # TODO: is it normal to write multiple times? project.write() # Release all file locks! If we don't do this, we won't be able to clean up # layer source files after zipping the project. project.clear()
def _setup_qgs_app() -> qgc.QgsApplication: """Set up QgsApplication. This function should only be called once to instantiate a QgsApplication. Once all pyqgis operations are complete, the QgsApplication MUST be cleaned up with the QgsApplication instance's `exitQgis` method. Failure to do so will result in a segmentation fault. """ qgis_prefix_path = _get_qgs_prefix_path() # Boilerplate QGIS initialization code; # - Suppresses "Application path not intialized" errors # - Enables Qt support for fonts used in layer styles (labels) qgs = qgc.QgsApplication([], False) qgs.initQgis() qgc.QgsApplication.setPrefixPath(str(qgis_prefix_path), True) return qgs
def setUp(self): self.app = core.QgsApplication([], True) propertize(core)
Usage: run myproject.qgs /path/to/output """ if __name__ == "__main__": import sys import os from qgis.PyQt.QtCore import QFileInfo import qgis.core as Q sys.path.append(os.path.dirname(__file__)) import main qgs = Q.QgsApplication([], False) qgs.initQgis() project_path = sys.argv[1] out_dir = sys.argv[2] if not os.path.exists(project_path): print project_path, 'not found' sys.exit(1) try: os.mkdir(out_dir) except OSError: pass print 'loading...'
import sys import os from qgis.core import QgsApplication import qgis.core as qt # Initialize QGIS qt.QgsApplication.setPrefixPath("C:\\OSGeo4W64\\apps\\qgis", True) qgs = qt.QgsApplication([], False) qgs.initQgis() # Add the path to processing sys.path.append('C:\OSGeo4W64\apps\qgis\python\plugins') # Import processing import processing def create_map(shp_file, csv_f): assert os.path.exists( shp_file ), "I could not locate the shape file. Was the path typed correctly?" s = open(shp_file, 'r+') print("Shape File Located") # Add Georgia Map to Canvas ga_map = qt.QgsVectorLayer(shp_file, "GA Map", "ogr") qt.QgsProject.instance().addMapLayer(ga_map) s.close() csv_uri = csv_f + "?encoding=UTF-8&delimiter=,"
group_name="CHM 2011", style_file="D:/Lb/Maps/QGIS_styles/CHM.qml") # Get list of files in_files = [f for f in os.listdir(a.RSDS_folder) if f.endswith(a.file_ext)] if len(in_files) > 0: # Get full file paths in_paths = [os.path.join(a.RSDS_folder, f) for f in in_files] # Get names of layers in_names = [os.path.splitext(f)[0] for f in in_files] # Launch QGIS application qgs = qc.QgsApplication([], True) qgs.initQgis() # WARNING: This is to silence the ol 'Sum of Photometric type-related... (etc)' error # Should be included with caution, since it can silence other errors PushErrorHandler('CPLQuietErrorHandler') # Create new project project = qc.QgsProject() # Read map project.read(a.qgs_file) # To access layers and groups at root root = project.layerTreeRoot()
def _init_qgis(): qgs = qgc.QgsApplication([], False) qgs.initQgis() qgc.QgsApplication.setPrefixPath(_get_prefix_path(), True)