Redirect stdout & stderr (similar to a daemon)
Eric S. Johansson
esj at harvee.org
Sun May 30 10:20:18 EDT 2004
Tsai Li Ming wrote:
> Dear all,
>
> I have a problem with a redirecting stdout and stderr. I am a top level
> module and has no control over the imported modules that are making
> system calls such as os.system or popen2.* . I have tried the simplest
> method of capturing stdout, stderr via:
>
> saveout = sys.stdout
> sys.stdout = file_obj
>
> print 1 # works
> os.system('w') # Doesn't work
>
> sys.stdout = saveout
> print 1 # Restored
>
> ------------------------------------------------
>
> Therefore, I changed to the following method, similar
> to a daemon. However, I couldn't find a way to restore back stdout and
> stderr.
if I understand what you're looking to do, I solved a similar problem by
pushing the redirection of standard out and standard error into the
command that I executed.
baseline_command ="somecommand 2> <temporary filename> 1> /dev/null"
and then on executing the command, standard I/O is redirected in the
child process which eliminates the need to manipulate it in your
program. The program fragment below should get you started. As you can
see, it executes the command and then if the error file is non zero
length, you retrieve the data and do something with it. The same
technique can be applied to standard out just as easily.
command_pipe = os.popen(command, "w")
command_pipe.write(trapped_message.as_string(1))
result = command_pipe.close()
if os.path.getsize(error_path) != 0:
for line in file(error_path).readlines():
log("command error %s"% line)
os.remove(error_path)
hope this is close to what you need
More information about the Python-list
mailing list