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.
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:
runping
.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.
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.
Run the runping
script in the Processing Toolbox GUI by double-clicking on it. Its execution will produce the following screenshot:
This shows progress in the progress bar of the Processing Toolbox and the output of the command in the Python console.
3.144.252.140