popen and exit code on Windows
Giovanni Bajo
noway at sorry.com
Tue Mar 7 03:42:00 EST 2006
iker.arizmendi at gmail.com wrote:
> On UNIX one can use popen* to get a pipe for reading, a pipe for
> writing, and the exit code of the child process via a call to close()
> on the last pipe. Is there any way, in principle, to simulate such
> behaviour on Windows? Some googling reveals that direct use of the
> popen* functions on Windows will not do the trick, but are there
> indirect ways?
This is well-tested:
def launch(cmd, split_lines=True):
"""Launch a sub-process. Return its output (both stdout and stderr),
optionally split by lines (if split_lines is True). Raise a LaunchError
exception if the exit code of the process is non-zero (failure)."""
if os.name not in ['nt', 'os2']:
p = popen2.Popen4(cmd)
p.tochild.close()
if split_lines:
out = p.fromchild.readlines()
else:
out = p.fromchild.read()
ret = p.wait()
if ret == 0:
ret = None
else:
ret >>= 8
else:
i,k = os.popen4(cmd)
i.close()
if split_lines:
out = k.readlines()
else:
out = k.read()
ret = k.close()
if ret is None:
return out
raise LaunchError(ret, cmd, out)
--
Giovanni Bajo
More information about the Python-list
mailing list