tags:

views:

101

answers:

2

hello everyone
Im no bash expert so bear with me

I have a python script thats starting other processes, which then emit log messages on stdout.
what bash command would I use to redirect stdout of those child processes back to the stdout of the parent process (the python script thats starting the processes)?

thank you in advance

+3  A: 

If you just want to capture the output of the child processes in your python script, the best way to do it would be to use the subprocess module:

import subprocess

p = subprocess.Popen(['/bin/ls', '-l'], stdout=subprocess.PIPE)
(out, _) = p.communicate()
print "Output:", out
sth
im doing that now but that only gives the output once the command has completed. however if its a long running process (some kind of server or something) I have to wait until exit to get at the stdout...
deepblue
You could experiment with `p.stdout.read()` and similar functions to read the incoming data incrementally. But be aware of the potential problems if the processes also produce output on stderr: http://docs.python.org/library/subprocess.html#subprocess.Popen.kill
sth
cool. that sounds like what I need. I'll put it in a loop and read/print stuff thats in there... thanks!
deepblue
@deepblue, you're likely to run into undesired buffering (emitting output only in bursts of 4K or so, for example) -- in which case, open another question **with** the full description of what you desire (and the response will be `pexpect` on non-Windows, `wexpect` on Windows, as usual to the many existing questions essentially identical to this one;-).
Alex Martelli
@Alex - basically you're right. i've spent at least an hour trying to get the stdout file object to give me lines of text inside a while loop via stdout.read()... no luck. Im reviewing pexpect, thank you very much for the tip!
deepblue
+1  A: 

I'm assuming you're using os.system("command") to execute your scripts. This method only executes the command and gives you the program's return value and NOT it's stdout. What you need is the subprocess module. For example:

import subprocess

proc = subprocess.Popen(['command', 'option 1', 'option 2'], stdout=subprocess.PIPE)
output = proc.communicate()[0] #for stdout. Use proc.communicate[1] for stderr

On looking at your comment, your solution is simple:

subprocess.Popen('command option 1 option 2', shell=True)

Note: command needs to be passed as a string. A sequence doesn't work.

Chinmay Kanchi
thats what Im doing now. look above for the problem with that
deepblue