PageRenderTime 21ms CodeModel.GetById 16ms RepoModel.GetById 0ms 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 | 7 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. See https://bitbucket.org/galaxy/galaxy-central/issue/325/
  4. Currently Galaxy ignores the return code from command line tools (even if it
  5. is non-zero which by convention indicates an error) and treats any output on
  6. stderr as an error (even though by convention stderr is used for errors or
  7. warnings).
  8. This script runs the given command line, capturing all stdout and stderr in
  9. memory, and gets the return code. For a zero return code, any stderr (which
  10. should be warnings only) is added to the stdout. That way Galaxy believes
  11. everything is fine. For a non-zero return code, we output stdout as is, and
  12. any stderr, plus the return code to ensure there is some output on stderr.
  13. That way Galaxy treats this as an error.
  14. Once issue 325 is fixed, this script will not be needed.
  15. """
  16. import sys
  17. import subprocess
  18. #Avoid using shell=True when we call subprocess to ensure if the Python
  19. #script is killed, so too is the BLAST process.
  20. try:
  21. words = []
  22. for w in sys.argv[1:]:
  23. if " " in w:
  24. words.append('"%s"' % w)
  25. else:
  26. words.append(w)
  27. cmd = " ".join(words)
  28. child = subprocess.Popen(sys.argv[1:],
  29. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  30. except Exception, err:
  31. sys.stderr.write("Error invoking command:\n%s\n\n%s\n" % (cmd, err))
  32. sys.exit(1)
  33. #Use .communicate as can get deadlocks with .wait(),
  34. stdout, stderr = child.communicate()
  35. return_code = child.returncode
  36. if return_code:
  37. sys.stdout.write(stdout)
  38. sys.stderr.write(stderr)
  39. sys.stderr.write("Return error code %i from command:\n" % return_code)
  40. sys.stderr.write("%s\n" % cmd)
  41. else:
  42. sys.stdout.write(stdout)
  43. sys.stdout.write(stderr)