PageRenderTime 5ms CodeModel.GetById 1ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/ncbi_blast_plus/hide_stderr.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 49 lines | 25 code | 2 blank | 22 comment | 5 complexity | 76428992d4bc2e41e0c21b05429393d0 MD5 | raw file
 1#!/usr/bin/env python
 2"""A simple script to redirect stderr to stdout when the return code is zero.
 3
 4See https://bitbucket.org/galaxy/galaxy-central/issue/325/
 5
 6Currently Galaxy ignores the return code from command line tools (even if it
 7is non-zero which by convention indicates an error) and treats any output on
 8stderr as an error (even though by convention stderr is used for errors or
 9warnings).
10
11This script runs the given command line, capturing all stdout and stderr in
12memory, and gets the return code. For a zero return code, any stderr (which
13should be warnings only) is added to the stdout. That way Galaxy believes
14everything is fine. For a non-zero return code, we output stdout as is, and
15any stderr, plus the return code to ensure there is some output on stderr.
16That way Galaxy treats this as an error.
17
18Once issue 325 is fixed, this script will not be needed.
19"""
20import sys
21import 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.
25try:
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)
35except 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(),
39stdout, stderr = child.communicate()
40return_code = child.returncode
41
42if 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)
47else:
48    sys.stdout.write(stdout)
49    sys.stdout.write(stderr)