get the return code when piping something to a python script?
chris
chris.levis at gmail.com
Wed Aug 17 10:23:42 EDT 2005
I use the following when I have an external command to do:
#----------------------------------------------------
def doCommand( cmd,forked=False,runFrom=None ):
"""
Do a command, and return the (stdout+stderr) and the exit status.
This was written to work both on Windows and *nix, and in the
limited
testing to which it has been subjected, it works well.
"""
import sys;
import os;
exitcode = None;
output = None;
origin = None;
if runFrom:
origin = os.getcwd()
try:
os.chdir( runFrom );
except:
pass;
# "forked" to us means "run in background and forget about it".
The
# method of execution is the same on both windows and unix
if forked:
theCommand = cmd.split()[0];
theArgs = cmd.split(); # Include the cmd itself in the
v.
# Guaranteed to be a list.
# P_DETACH: we don't want the process to be our child, and
# we don't want to know what happens to it... Some father!
exitstatus = os.spawnve(
os.P_DETACH,theCommand,theArgs,os.environ );
# if we're not spawning off a separate child, then we do care about
# the results of the process, and execution is different between
# windows and unix
else:
if( sys.platform == "win32" ):
import win32pipe;
(stdin,stdout) = win32pipe.popen4( cmd,'t' );
stdin.close();
output = stdout.read();
try:
exitcode = stdout.close() or 0;
except IOError:
exitcode = ( -1 );
else:
import commands;
( exitstatus,output ) = commands.getstatusoutput(cmd)
#---- exitstatus is a smashing of the return value and any
signal
# sent back from the child process... break them out.
exitcode = (( exitstatus >> 8) & 0xFF );
signal = ( exitstatus & 0xFF );
if runFrom:
#return( 0,"Returning to %s from %s" %(origin,os.getcwd()) )
os.chdir( origin );
return( exitcode,output );
#-----------------------------------------------------------
More information about the Python-list
mailing list