473,398 Members | 2,380 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Redirect stdout & stderr (similar to a daemon)

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.

import os
import sys

stdin = '/dev/null'
stdout = '/tmp/out.txt'
stderr = stdout

# Doesn't work
saveout = sys.stdout

si = file(stdin, 'r')
so = file(stdout, 'a+')
se = file(stderr, 'a+', 0)

# Redirect standard file descriptors.
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())

# Gets written to /tmp/out.txt
os.system('no_such_command')
os.system('w')
# How to do restoration of stdout and stderr
os.system('w')
print "Hello there"

Many thanks
Liming
Jul 18 '05 #1
6 5599
In article <40******@news.starhub.net.sg>,
Tsai Li Ming <ma*********@ltsai.com> wrote:
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
I think the problem here is that os.system runs a
shell with its own new set of process parameters,
including its own stdin, stdout, etc.

I would try one of the os.exec's or os.spawn's here
instead.
[ ... ]
# Redirect standard file descriptors.
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())


These modify the actual file objects represented by
'sys.stdin', etc. There's no coming back from that.

Regards. Mel.
Jul 18 '05 #2
Mel Wilson wrote:
In article <40******@news.starhub.net.sg>,
Tsai Li Ming <ma*********@ltsai.com> wrote:
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

I think the problem here is that os.system runs a
shell with its own new set of process parameters,
including its own stdin, stdout, etc.

I would try one of the os.exec's or os.spawn's here
instead.

[ ... ]
# Redirect standard file descriptors.
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())

These modify the actual file objects represented by
'sys.stdin', etc. There's no coming back from that.

Regards. Mel.


I would think so too. Sadly, I can't use other system calls because I
will be importing other modules that I have no control of.

Liming
Jul 18 '05 #3
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
Jul 18 '05 #4
Quoth mw*****@the-wire.com (Mel Wilson):
| In article <40******@news.starhub.net.sg>,
| Tsai Li Ming <ma*********@ltsai.com> wrote:
....
|> # Redirect standard file descriptors.
|> os.dup2(si.fileno(), sys.stdin.fileno())
|> os.dup2(so.fileno(), sys.stdout.fileno())
|> os.dup2(se.fileno(), sys.stderr.fileno())
|
| These modify the actual file objects represented by
| 'sys.stdin', etc. There's no coming back from that.

There is, if I understand what you meant by that. Consider

old0 = os.dup(0)
os.dup2(si.fileno(), 0)

The original input stream is held open on some arbitrary
unit, which you may use at any point to restore it to standard
input.

os.dup2(old0, 0)
os.close(old0)

Donn Cave, do**@drizzle.com
Jul 18 '05 #5
Donn Cave wrote:
Quoth mw*****@the-wire.com (Mel Wilson):
| In article <40******@news.starhub.net.sg>,
| Tsai Li Ming <ma*********@ltsai.com> wrote:
...
|> # Redirect standard file descriptors.
|> os.dup2(si.fileno(), sys.stdin.fileno())
|> os.dup2(so.fileno(), sys.stdout.fileno())
|> os.dup2(se.fileno(), sys.stderr.fileno())
|
| These modify the actual file objects represented by
| 'sys.stdin', etc. There's no coming back from that.

There is, if I understand what you meant by that. Consider

old0 = os.dup(0)
os.dup2(si.fileno(), 0)

The original input stream is held open on some arbitrary
unit, which you may use at any point to restore it to standard
input.

os.dup2(old0, 0)
os.close(old0)

Donn Cave, do**@drizzle.com


Thanks Donn,

Why is there a need to close old0? Because of the extra file handle?

Liming
Jul 18 '05 #6
Quoth Tsai Li Ming <ma*********@ltsai.com>:
| Donn Cave wrote:

| > There is, if I understand what you meant by that. Consider
| >
| > old0 = os.dup(0)
| > os.dup2(si.fileno(), 0)
| >
| > The original input stream is held open on some arbitrary
| > unit, which you may use at any point to restore it to standard
| > input.
| >
| > os.dup2(old0, 0)
| > os.close(old0)
| >
| > Donn Cave, do**@drizzle.com
|
| Thanks Donn,
|
| Why is there a need to close old0? Because of the extra file handle?

Good question. It's just barely conceivable that it could cause a
problem - say, where a child process redirects 0 but doesn't account
for the dup'd version, the parent exits, the file stays open when
it should have closed on exit, and something else has been depending
on that. To start with, most normal ways to fork a child process
will close all the extra files anyway, so this is highly improbable.

I would still do it, but it's more style than function.

Donn Cave, do**@drizzle.com
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: newgene | last post by:
Hi, group, I guess it is a simple question for you, but it puzzles me for a while. I use a wxTextCtrl in my application for output result and any exception msg. I know I can add new msg onto...
2
by: Hans Deragon | last post by:
Greetings. I am performing: commands.getstatusoutput("rsync <params>"); rsync takes a long time and prints out a steady stream of lines showing which file it is currently working on.
3
by: ladygrinningsoul | last post by:
I have a Perl program which runs a number of external programs. I want to be able to read both stdout and stderr into separate variables. The 'Perl Cookbook' states (I quote): To read both a...
1
by: SG | last post by:
Hello, I'm using _execvpe (Win32 console project in VS.NET) to spawn a child process. I would like to know if you have any pointers on how to capture the child's STDOUT and STDERR? Any help is...
5
by: Martijn Brouwer | last post by:
I am writing a unix daemon in python, so I want to close stdin, stdout and stderr. My first attempt was to the standard file descriptors using their close() methods. After closing stdout, I could...
4
by: robert | last post by:
when I run a command myapp 2>&1 yet: #!python print os.popen("myapp 2>&1").read()
3
by: mikem76 | last post by:
How do I automatically redirect stdout and stderr when using os.popen2 to start a long running process. If the process prints a lot of stuff to stdout it will eventually stop because it runs out...
10
by: Jef Driesen | last post by:
I wrote a program that writes a large amount of information to stdout (and stderr). When run from the commandline, this output either appears on the console window (the default) or can be...
4
by: lovecreatesbea... | last post by:
For example, in Bourne Shell both stdout and stderr can be re-directed to /dev/null, $ ./a.out 2>&1 /dev/null then is there any difference still?
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.