[Tutor] Capture command output

Johan Geldenhuys johan at accesstel.co.za
Thu Nov 3 08:37:14 CET 2005

I've been musy with the os command on how to kill a process. That's been 
sorted out to an extend. Many thanks for your input.

Now I have a question in the same direction:

I use os.execpv(cmd, [cmd, args]). That executes the command that have 
output. This was the best way of getting the pid and killing the process 
after a certain time.

This is my code:
import os, signal, time
pid = os.fork()
print 'pid; ',pid
if pid == 0: #child process
   os.execvp('tcpdump', ['tcpdump', '-np'])  # Need syntax to add 
another arg
time.sleep(5) # let it run for 5 seconds
kill(pid) # kill the process

def kill(pid, signal=signal.SIGTERM):
   print "trying to kill pid...", pid
   os.kill(pid, signal)
   os.waitpid(pid, 0)
   print "Killed %d"%pid

How do I capture that output to a file?
Can I use os.popen() or something like that after I did the os.execvp() 
execution or is there a standard way of putting any output in a file/


More information about the Tutor mailing list