comparison hide_stderr.py @ 0:d375502056f1 draft

Uploaded
author devteam
date Fri, 17 Aug 2012 09:11:43 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:d375502056f1
1 #!/usr/bin/env python
2 """A simple script to redirect stderr to stdout when the return code is zero.
3
4 See https://bitbucket.org/galaxy/galaxy-central/issue/325/
5
6 Currently Galaxy ignores the return code from command line tools (even if it
7 is non-zero which by convention indicates an error) and treats any output on
8 stderr as an error (even though by convention stderr is used for errors or
9 warnings).
10
11 This script runs the given command line, capturing all stdout and stderr in
12 memory, and gets the return code. For a zero return code, any stderr (which
13 should be warnings only) is added to the stdout. That way Galaxy believes
14 everything is fine. For a non-zero return code, we output stdout as is, and
15 any stderr, plus the return code to ensure there is some output on stderr.
16 That way Galaxy treats this as an error.
17
18 Once issue 325 is fixed, this script will not be needed.
19 """
20 import sys
21 import subprocess
22
23 #Avoid using shell=True when we call subprocess to ensure if the Python
24 #script is killed, so too is the BLAST process.
25 try:
26 words = []
27 for w in sys.argv[1:]:
28 if " " in w:
29 words.append('"%s"' % w)
30 else:
31 words.append(w)
32 cmd = " ".join(words)
33 child = subprocess.Popen(sys.argv[1:],
34 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
35 except Exception, err:
36 sys.stderr.write("Error invoking command:\n%s\n\n%s\n" % (cmd, err))
37 sys.exit(1)
38 #Use .communicate as can get deadlocks with .wait(),
39 stdout, stderr = child.communicate()
40 return_code = child.returncode
41
42 if return_code:
43 sys.stdout.write(stdout)
44 sys.stderr.write(stderr)
45 sys.stderr.write("Return error code %i from command:\n" % return_code)
46 sys.stderr.write("%s\n" % cmd)
47 else:
48 sys.stdout.write(stdout)
49 sys.stdout.write(stderr)