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

Larry Shaffer larrys at dakotacarto.com
Tue Mar 18 08:44:05 PDT 2014


Hi Hugo,

On Tue, Mar 18, 2014 at 2:59 AM, Hugo Ledoux <h.ledoux at tudelft.nl> wrote:

> 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()
>

Though I have not tested whether this is better on Windows, try instead:

  print p.communicate()[0]

See:
http://docs.python.org/2.7/library/subprocess.html#subprocess.Popen.communicate

I had a similar file handle issues on Mac, and that fixed it (though it
seems like p.stdout.read() should just work).

Regards,

Larry

...
>
> 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
> _______________________________________________
> Qgis-developer mailing list
> Qgis-developer at lists.osgeo.org
> http://lists.osgeo.org/mailman/listinfo/qgis-developer
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20140318/85cff827/attachment.html>


More information about the Qgis-developer mailing list