Is there a way for adding new Processing scripts into Processing toolbox using PyQGIS?
In the GUI, I can click on "Add script to toolbox", but I want to add scripts using PyQGIS.
QGIS version: 3.16
Is there a way for adding new Processing scripts into Processing toolbox using PyQGIS?
In the GUI, I can click on "Add script to toolbox", but I want to add scripts using PyQGIS.
QGIS version: 3.16
If you want to have the same action as Add Script to Toolbox..., execute the code below :
# import the script
from processing.script.AddScriptFromFileAction import AddScriptFromFileAction
# get the reference to the current processing toolbox
toolbox = iface.mainWindow().findChild(QgsDockWidget, "ProcessingToolbox")
# create an instance
script_add = AddScriptFromFileAction()
# add the reference to the current toolbox
script_add.toolbox = toolbox
# execute the script to open a Python script
script_add.execute()
You can look at what the AddScriptFromFileAction
do in this script.
You can do that using the code snippet below (adapted from the QGIS Resource Sharing plugin):
import os.path
import shutil
import glob
from processing.script import ScriptUtils
my_scripts_dir = "/path/to/your/scripts/"
count = 0
qgis_scripts_dir = ScriptUtils.defaultScriptsFolder()
# Copy scripts from your script dir to QGIS script dir
for filename in glob.glob(os.path.join(my_scripts_dir, '*.py')):
try:
shutil.copy(filename, qgis_scripts_dir)
count += 1
except OSError as e:
print("Couldn't install script '{}'!".format(filename))
# Finally, refresh the algorithms for the Processing script provider
if count:
QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
Note: If you are going to add your scripts while QGIS is starting, you will need to check that the script
provider is already set. Something like:
if QgsApplication.processingRegistry().providerById('script'):
...
Just copy the pythonscript to the user profiles folder, e.g. under windows it would be: C:\Users\username\AppData\Roaming\QGIS\QGIS3\profiles\profilename\processing\scripts
as a python script it would be something like:
import shutil
shutil.copy2('/src/dir/myprocess.py', 'C:/Users/username/AppData/Roaming/QGIS/QGIS3/profiles/profilename/processing/scripts/myprocess.py')
you have to adjust username and profilename in the path. the default profilename is in QGIS: default