Newbie - Running Commands Interactively

Chris Bingham chris at
Mon Mar 13 10:54:09 CET 2006

Hi everyone,

I'm new to python, and I was wondering if anyone could help me with a
couple of problems I've hit please?

I'm trying to write a wrapper script for the passwd command, so that we
can log everytime someone uses it, which options they used with it and
if they succeeded or cancelled the command. The idea is that it'll look
to the user like they're running the original system passwd command,
but actually they're running it though this script.

At the moment my script looks like this:

#!/usr/bin/env python

import os
import coLog
import sys

if len(sys.argv) > 1:
      for arg in sys.argv[1:]:
            cmd=cmd + " " + arg


print result
print subResult

if subResult != '-1':
      coLog.add('Passwd', 'The user successfully executed the following
command: ' + cmd, 'CLI')
      coLog.add('Passwd', 'The user executed the following command, but
it failed or was cancelled: ' + cmd, 'CLI')


The 'coLog' module that get's imported at the start is 1 I wrote to do
the actual logging, so that i can easily reuse the code in other

I've got 2 problems with it that i just haven't been able to fix;

1. Firstly, if I use os.popen to execute the command, the first & last
lines of the command's output don't get displayed, i can get them later
from the 'cmdRun' variable and print them, but then it doens't look
like the original passwd command. I've found that using os.system
instead fixes this issue, but then pressing ctrl-c during the command
causes the shell ure in to go cooco-lala on u! :) os.popen works
correctly with ctrl-c. I also tried os.popen2, but this caused the
passwd command to go nuts!

2. Secondly, if ctrl-c is pressed the script gets killed along with the
command, so it doens't log cancelled commands. I've tried using various
variations of 'try, except', including catching the KeyboardInterrupt
and catching all exceptions, but nothing seemed to work!

I've been struggling with these 2 issues for the last week, and so far
no joy. If anyone has any idea how to fix them I'd really appreciate
the help! :)

Thanks in advance for any help anybody can give,


More information about the Python-list mailing list