Adding scripts to Processing toolbox via PyQGIS
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'):
...