PyQGIS Standalone – Running PyQGIS Without Using the GUI

macospyqgisstandalone

I found this topic and it is exactly what I want to do. As @casta2k in 2015 I am running MacOS.

So I follow the step and that is what I get :

>>> import sys
>>> import os
>>> sys.path.append("/Applications/QGIS-LTR.app/Contents/Resources/python")
>>> from qgis.core import *
    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Applications/QGIS-LTR.app/Contents/Resources/python/qgis/core/__init__.py", line 25, in <module>
    from qgis._core import *
ImportError: dlopen(/Applications/QGIS-LTR.app/Contents/Resources/python/qgis/_core.so, 0x0002): Library not loaded: @rpath/qgis_core.framework/Versions/3.22/qgis_core
  Referenced from: /Applications/QGIS-LTR.app/Contents/Resources/python/qgis/_core.so
  Reason: tried: '/System/Library/Frameworks/qgis_core.framework/Versions/3.22/qgis_core' (no such file)
>>>

So I checked [this][3]. The solution seem to be simple, just run python3 from :

/Applications/QGIS-LTR.app/Contents/MacOS/bin/

That is what I have done, I am currently stuck as @casta2k were in 2015… That is what I got :

pugliesipc@Pierres-MacBook-Air ~ % /Applications/QGIS-LTR.app/Contents/MacOS/bin/python3.8
Python 3.8.7 (default, Feb 10 2021, 09:04:08) 
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> sys.path.append("/Applications/QGIS.app/Contents/Resources/python")
>>> from qgis.core import *
>>> import qgis.utils
>>> from qgis.analysis import *
>>> QgsApplication.setPrefixPath("/Applications/QGIS-LTR.app/Contents/MacOS", True)
>>> QgsApplication.initQgis()
zsh: segmentation fault  /Applications/QGIS-LTR.app/Contents/MacOS/bin/python3.8
pugliesipc@Pierres-MacBook-Air ~ %

I also tried to run my script but it did not work as you can see :

pugliesipc@Pierres-MacBook-Air ~ % /Applications/QGIS-LTR.app/Contents/MacOS/bin/python3.8
Python 3.8.7 (default, Feb 10 2021, 09:04:08) 
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> sys.path.append("/Applications/QGIS.app/Contents/Resources/python")
>>> from qgis.core import *
>>> import qgis.utils
>>> from qgis.analysis import *
>>> QgsApplication.setPrefixPath("/Applications/QGIS-LTR.app/Contents/MacOS", True)
>>> exec(open('/Users/pugliesipc/Desktop/Phase_2/python/Coordonnees.py'.encode('utf-8')).read())
<stdin>:1: ResourceWarning: unclosed file <_io.TextIOWrapper name=b'/Users/pugliesipc/Desktop/Phase_2/python/Coordonnees.py' mode='r' encoding='UTF-8'>
ResourceWarning: Enable tracemalloc to get the object allocation traceback
ERROR 1: PROJ: proj_create_from_database: Cannot find proj.db
proj_create_from_database: Cannot find proj.db
proj_create_from_database: Cannot find proj.db
proj_create_from_database: Cannot find proj.db
proj_create_from_database: Cannot find proj.db
proj_create_from_wkt: Cannot find proj.db
proj_identify: Cannot find proj.db
proj_create_from_database: Cannot find proj.db
proj_create_from_database: Cannot find proj.db
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 26, in <module>
  File "<string>", line 21, in shp
NameError: name 'processing' is not defined
>>> 

Just in case that is my script :

def shp(a,b,c):

    format_tuiles=[c,b,a] # Dans l'ordre décroissant pour une bonne superposition des couches

    background=QgsRasterLayer('/Users/pugliesipc/Desktop/Phase_2/background/S2_31aout2017_432_UTM32.tif','background')
    QgsProject.instance().addMapLayer(background)

    for px in format_tuiles:
        
        processing.run('native:buffer',{'DISSOLVE':False,'DISTANCE':px*2.5,'END_CAP_STYLE':2,'INPUT':'delimitedtext://file:///Users/pugliesipc/Desktop/extract_windows/data/data_v9.csv?delimiter=;&decimalPoint=,&crs=epsg:32632&xField=UTM32_E&yField=UTM32_N','JOIN_STYLE':1,'MITER_LIMIT':2,'OUTPUT':'/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/'+str(px)+'px/'+str(px)+'px.shp','SEGMENTS':1})
        layer=QgsVectorLayer('/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/'+str(px)+'px/'+str(px)+'px.shp',str(px)+'px','ogr')
        QgsProject.instance().addMapLayer(layer)
        print(str(px)+'px')

shp(1,3,11)

def extract_stats(a,b,c):

    import os # Ce module permet d'utiliser les fonctionnalités du système d'exploitation
    import pandas as pd # Ce module facilite l'exploitation des fichiers CSV

    format_tuiles=[a,b,c]
    output=[pd.DataFrame()]*3
    radar_image='/Users/pugliesipc/Desktop/extract_windows/TSX/CCOH_21_22'

    list_radar_image=os.listdir(radar_image)

    vlyr_1px=QgsVectorLayer('/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/1px/1px.shp','1px','ogr')
    vlyr_3px=QgsVectorLayer('/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/3px/3px.shp','1px','ogr')
    vlyr_11px=QgsVectorLayer('/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/11px/11px.shp','1px','ogr')

    for file in list_radar_image:

        i=0
        date=file[14:16]+'/'+file[12:14]+'/'+file[8:12]
        path_to_radar_output=radar_image+'/'+file
        print(date)

        for px in format_tuiles:
            processing.run('native:zonalstatisticsfb',{'COLUMN_PREFIX':'_','INPUT':'/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/'+str(px)+'px/'+str(px)+'px.shp','INPUT_RASTER':path_to_radar_output,'OUTPUT':'/Users/pugliesipc/Desktop/extract_windows/Shapefile_stat/'+str(px)+'px/'+str(px)+'px.shp','RASTER_BAND':1,'STATISTICS':[2]})
            processing.run('native:savefeatures',{'DATASOURCE_OPTIONS':'','INPUT':'/Users/pugliesipc/Desktop/extract_windows/Shapefile_stat/'+str(px)+'px/'+str(px)+'px.shp','LAYER_NAME':'','LAYER_OPTIONS':'','OUTPUT':'/Users/pugliesipc/Desktop/extract_windows/Sortie_txt/CCOH_21_22/output'+str(px)+'.csv'})
            temporary_csv=pd.read_csv('/Users/pugliesipc/Desktop/extract_windows/Sortie_txt/CCOH_21_22/output'+str(px)+'.csv')
            output[i]=pd.concat([output[i],temporary_csv,pd.DataFrame.from_records([{'Date':'#','Name':'#','UTM32_E':'#','UTM32_N':'#','_mean':'#'}])])
            i+=1

    i=0

    for px in format_tuiles: 
        output[i].to_csv('/Users/pugliesipc/Desktop/extract_windows/Sortie_txt/CCOH_21_22/output_'+str(px)+'px.csv')
        i+=1

extract_stats(1,3,11)

If someone could explain me how to fix this it would be amazing

Best Answer

This code do the trick for me :

# Prepare the environment

import sys
import os
from qgis.core import *
from PyQt5.QtWidgets import QApplication
app = QApplication([])
QgsApplication.setPrefixPath("/Applications/QGIS-LTR.app/Contents/MacOS", True)
os.environ["PROJ_LIB"]="/Applications/QGIS-LTR.app/Contents/Resources/proj"
QgsApplication.initQgis()

# Prepare processing framework 

sys.path.append('/Applications/QGIS-LTR.app/Contents/Resources/python/plugins') # Path to the file 'processing' (depending of your QGIS version it could be different)
from processing.core.Processing import Processing
Processing.initialize()
import processing

# Run the algorithm

def shp(a,b,c):

    format_tuiles=[c,b,a]

    for px in format_tuiles:
        
        processing.run('native:buffer',{'DISSOLVE':False,'DISTANCE':px*2.5,'END_CAP_STYLE':2,'INPUT':'delimitedtext://file:///Users/pugliesipc/Desktop/extract_windows/data/data_v9.csv?delimiter=;&decimalPoint=,&crs=epsg:32632&xField=UTM32_E&yField=UTM32_N','JOIN_STYLE':1,'MITER_LIMIT':2,'OUTPUT':'/Users/pugliesipc/Desktop/extract_windows/shapefiles_windows/'+str(px)+'px/'+str(px)+'px.shp','SEGMENTS':1})
        print(str(px)+'px')

shp(1,3,11)

# Exit applications

QgsApplication.exitQgis()
QApplication.exit()

References :

Related Question