Getting subprocess.call() output into a string?
Nick Stinemates
nick at stinemates.org
Fri Apr 18 15:10:00 EDT 2008
On Tue, Apr 15, 2008 at 11:16:01PM +0200, David wrote:
> >
> > Still, about StringIO...
> >
>
> The module description says you can use it to read and write strings
> as files, not that you can use strings *everywhere* you can use files.
>
> In your specific case, StringIO doesn't work, because the stdout
> redirection takes place at the operating system level (which uses real
> file handles), rather than in a python library (for which StringIO
> would probably work).
>
> David.
> --
> http://mail.python.org/mailman/listinfo/python-list
Just a note to all of those who are interested.
I have yet to get this to work properly for an app which runs indefinitely and you want to read the output at a specified interval. Right now the only way I can read is if the _close() method has been called.
Anyway, I wrote a wrapper around it so I could easily change the
implementation if I could ever find a better solution. Here's my code:
===========================
import subprocess
import os
import select
class ProcessMonitor:
def __init__(self):
self.__process = None
self.__stdin = None
self.__stdout = None
def _create(self, process):
self.__process = subprocess.Popen(process, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
self.__stdin = self.__process.stdout
self.__stdout = self.__process.stdout
def _close(self):
os.kill(self.__process.pid,9)
def _listen(self):
"""
get from stdout
"""
return "".join(self.__stdout.readlines())
def _listen2(self):
"""
My attempt at trying different things.
"""
inp, out = self.__process.communicate("")
print out
--
Nick Stinemates (nick at stinemates.org)
http://nick.stinemates.org
More information about the Python-list
mailing list