Running an external algorithm or command

There are often a bunch of legacy programs or scripts for which there are no resources to port them into another language or framework. Thanks to Python and PyQGIS, it's simple to integrate your existing programs into QGIS.

Running a simple command

We can run an external command in different ways, but we will explore how to do it with the Processing Toolbox that supports the progress bar, which is often useful to log algorithm steps.

To execute an external command, we will follow these steps:

  1. Create a Processing Toolbox script called runping.
  2. Code the script.
  3. Test the script.

Step one is similar to that described in the Creating a test Processing Toolbox script section.

The code of the script is in the following code snippet:

import subprocess
import time

proc = subprocess.Popen(
    ["ping", "-c", "10", "localhost"],
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE,
    stderr=subprocess.PIPE)

counter = 0
for line in iter(proc.stdout.readline, ''):
    print line
    progress.setPercentage(counter)
    counter += 10

The preceding code runs the ping command to localhost and stops after 10 pings.

Tip

In case of Windows operating systems, replace ["ping", "-c", "10", "localhost"] with ["ping", "-n", "10", "localhost"].

There are different ways to run a system command in Python. The preceding method, using the subprocess module, allows a non-blocking run and interaction with the program using the stdin pipe.

After creating a subprocess.Popen pipe, the code snippet starts a for loop to read the standard output of the stdout program printing the messages in the console.

Tip

If your command is stuck in the QGIS interface, try to wrap it in a Python script and run the wrapper with ["python", "-i", "<your command wrapper>"], where your command wrapper could be simply a one-line code such as import os; os.system("<your command>").

Run the runping script in the Processing Toolbox GUI by double-clicking on it. Its execution will produce the following screenshot:

Running a simple command

This shows progress in the progress bar of the Processing Toolbox and the output of the command in the Python console.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.140