"""$URL: svn://svn/repos/trunk/sitereaper/lib/utils.py $
$Id: utils.py 20952 2003-03-05 16:51:11Z dbinger $

Miscellaneous utility functions needed by other sitereaper modules.
"""

import sys, os

# Pseudo-method that can be used in any class
def std_repr (self):
    if hasattr(self, '__str__'):
        return "<%s at %x: %s>" % (self.__class__.__name__, id(self), self)
    else:
        return "<%s at %x>" % (self.__class__.__name__, id(self))

def warn (msg):
    sys.stderr.write("warning: %s\n" % msg)


def _exec (argv):
    try:
        os.execvp(argv[0], argv)
    except OSError, err:
        os.write(2, "couldn't exec %s: %s\n" % (argv[0], err.strerror))
    except:
        os.write(2, "couldn't exec %s\n" % argv[0])
    os._exit(1)


def spawn_pipe_r (argv, bufsize=-1):
    """spawn_pipe_r(argv : [string], bufsize : int = -1)
       -> (pid : int, child_stdout : file)

    Spawn a child process; return the PID of the child and a readable
    file object connected to the child's stdout.  (The child's stdin and
    stderr are the same as the parent's.)
    """
    (fd_r, fd_w) = os.pipe()
    pid = os.fork()
    if pid == 0:                        # in the child
        os.dup2(fd_w, 1)                # connect stdout to the parent
        os.close(fd_r)                  # not needed here
        _exec(argv)
    else:                               # in the parent
        os.close(fd_w)
        child_stdout = os.fdopen(fd_r, "r", bufsize)
        return (pid, child_stdout)
