~launchpad-pqm/launchpad/devel

10850.1.1 by Bjorn Tillenius
Pass -S to shhh.py's python, to get rid of "'import site' failed" errors when running make.
1
#! /usr/bin/python -S
8687.15.4 by Karl Fogel
Add the copyright header block to more files; tweak format in a few files.
2
#
3
# Copyright 2009 Canonical Ltd.  This software is licensed under the
4
# GNU Affero General Public License version 3 (see the file LICENSE).
5
1831 by Canonical.com Patch Queue Manager
New config machinery, database helpers and oddsnsods required for staging
6
"""
7
Run a command and suppress output unless it returns a non-zero exit status
8
"""
9
10
__metaclass__ = type
11
12
import sys
13
from subprocess import Popen, PIPE
14
15
def shhh(cmd):
16
    r"""Run a command and suppress output unless it returns a non-zero exitcode
17
18
    If output is generated, stderr will be output before stdout, so output
19
    order may be messed up if the command attempts to control order by
20
    flushing stdout at points or setting it to unbuffered.
21
22
23
    To test, we invoke both this method and this script with some commands
24
    and examine the output and exitvalue
25
26
    >>> python = sys.executable
27
28
    >>> def shhh_script(cmd):
29
    ...     from subprocess import Popen, PIPE
30
    ...     script = '%s %s' % (python, __file__)
31
    ...     cmd = "%s '%s'" % (script, cmd)
32
    ...     p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
33
    ...     (out, err) = p.communicate()
34
    ...     return (out, err, p.returncode)
35
36
    >>> cmd = '''%s -c "import sys; sys.exit(%d)"''' % (python, 0)
37
    >>> shhh(cmd)
38
    0
39
    >>> shhh_script(cmd)
40
    ('', '', 0)
41
42
    >>> cmd = '''%s -c "import sys; sys.exit(%d)"''' % (python, 1)
43
    >>> shhh(cmd)
44
    1
45
    >>> shhh_script(cmd)
46
    ('', '', 1)
47
48
    >>> cmd = '''%s -c "import sys; print 666; sys.exit(%d)"''' % (
49
    ...     python, 42)
50
    >>> shhh(cmd)
51
    666
52
    42
53
    >>> shhh_script(cmd)
54
    ('666\n', '', 42)
55
56
    >>> cmd = (
57
    ...     '''%s -c "import sys; print 666; '''
58
    ...     '''print >> sys.stderr, 667; sys.exit(42)"''' % python
59
    ...     )
60
    >>> shhh_script(cmd)
61
    ('666\n', '667\n', 42)
62
    """
63
64
    process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
65
    (out, err) = process.communicate()
66
    if process.returncode == 0:
67
        return 0
68
    else:
69
        sys.stderr.write(err)
70
        sys.stdout.write(out)
71
        return process.returncode
72
73
74
if __name__ == '__main__':
75
    cmd = ' '.join(sys.argv[1:])
76
    sys.exit(shhh(cmd))
77