[Qgis-developer] how to run an external program from QGIS and catch its output?

Hugo Ledoux h.ledoux at tudelft.nl
Tue Mar 18 01:59:55 PDT 2014


I’m developing a plugin and I want to call an external program that
takes as input a string and outputs a string. Under Mac and Linux I
successfully used subprocess.Popen() but under Windows it doesn’t
work. For instance, from a Python console inside QGIS under Mac/Linux:

import subprocess
p = subprocess.Popen(['ls', '-al'], stdout=subprocess.PIPE)
print p.stdout.read()
total 17101
drwxr-xr-x   35 root  wheel     1258 Mar 13 09:11 .
drwxr-xr-x   35 root  wheel     1258 Mar 13 09:11 ..
-rw-rw-r--@   1 root  admin     6148 Dec  6 12:13 .DS_Store
d--x--x--x    8 root  wheel      272 Nov  5 10:02 .DocumentRevisions-V100
…

But under Windows if I try to catch the output (which is a requirement for me) :
import subprocess
p = subprocess.Popen(['dir'], shell=True, stdout=subprocess.PIPE)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\PROGRA~1\QGISVA~1\apps\Python27\lib\subprocess.py", line
703, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "C:\PROGRA~1\QGISVA~1\apps\Python27\lib\subprocess.py", line
839, in _get_handles
    p2cread = self._make_inheritable(p2cread)
  File "C:\PROGRA~1\QGISVA~1\apps\Python27\lib\subprocess.py", line
878, in _make_inheritable
    _subprocess.DUPLICATE_SAME_ACCESS)
WindowsError: [Error 6] The handle is invalid

What’s the best way to call a program and catching the output (a
string) under Windows?

Many thanks,
Hugo


More information about the Qgis-developer mailing list