summaryrefslogtreecommitdiffstats
path: root/displayconfig/execwithcapture.py
blob: 10c8e23e2a20c280b39cb11e7d7e917a813bca54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python

import os
import select

############################################################################
def ExecWithCapture(command, argv, searchPath = 0, root = '/', stdin = 0,
        catchfd = 1, closefd = -1):

    if not os.access(root + command, os.X_OK) and not searchPath:
        raise RuntimeError, command + " can not be run"

    (read, write) = os.pipe()
    childpid = os.fork()
    if (not childpid):
        if (root and root != '/'): os.chroot(root)
        os.dup2(write, catchfd)
        os.close(write)
        os.close(read)

        if closefd != -1:
            os.close(closefd)
        if stdin:
            os.dup2(stdin, 0)
            os.close(stdin)
        if searchPath:
            os.execvp(command, argv)
        else:
            os.execv(command, argv)
        sys.exit(1)
    os.close(write)

    rc = ""
    s = "1"
    while s:
        select.select([read], [], [])
        s = os.read(read, 1000)
        rc = rc + s

    os.close(read)

    try:
        os.waitpid(childpid, 0)
    except OSError, (errno, msg):
        print __name__, "waitpid:", msg

    return rc