Mercurial > repos > nilesh > bcftools
comparison bcftools_wrapper.py @ 2:14567aa2be12 draft default tip
Added wrapper script for correct stderr handling
| author | geert-vandeweyer |
|---|---|
| date | Thu, 10 Apr 2014 09:44:09 -0400 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 1:3182c7fac413 | 2:14567aa2be12 |
|---|---|
| 1 #!/usr/bin/env python | |
| 2 | |
| 3 """ | |
| 4 Wrapper that execute a program and its arguments but reports standard error | |
| 5 messages only if the program exit status was not 0 | |
| 6 Example: ./stderr_wrapper.py myprog arg1 -f arg2 | |
| 7 | |
| 8 Taken from bcftools_view package of gregory-minevich | |
| 9 """ | |
| 10 | |
| 11 import sys, subprocess | |
| 12 | |
| 13 assert sys.version_info[:2] >= ( 2, 4 ) | |
| 14 | |
| 15 def stop_err( msg ): | |
| 16 sys.stderr.write( "%s\n" % msg ) | |
| 17 sys.exit() | |
| 18 | |
| 19 def __main__(): | |
| 20 # Get command-line arguments | |
| 21 args = sys.argv | |
| 22 # Remove name of calling program, i.e. ./stderr_wrapper.py | |
| 23 args.pop(0) | |
| 24 # If there are no arguments left, we're done | |
| 25 if len(args) == 0: | |
| 26 return | |
| 27 | |
| 28 # If one needs to silence stdout | |
| 29 #args.append( ">" ) | |
| 30 #args.append( "/dev/null" ) | |
| 31 | |
| 32 cmdline = " ".join(args) | |
| 33 try: | |
| 34 # Run program | |
| 35 proc = subprocess.Popen( args=cmdline, shell=True, stderr=subprocess.PIPE ) | |
| 36 returncode = proc.wait() | |
| 37 # Capture stderr, allowing for case where it's very large | |
| 38 stderr = '' | |
| 39 buffsize = 1048576 | |
| 40 try: | |
| 41 while True: | |
| 42 stderr += proc.stderr.read( buffsize ) | |
| 43 if not stderr or len( stderr ) % buffsize != 0: | |
| 44 break | |
| 45 except OverflowError: | |
| 46 pass | |
| 47 # Running BCFtools failed: write error message to stderr | |
| 48 if returncode != 0: | |
| 49 raise Exception, stderr | |
| 50 except Exception, e: | |
| 51 # Running BCFtools failed: write error message to stderr | |
| 52 stop_err( 'Error:\n' + str( e ) ) | |
| 53 | |
| 54 | |
| 55 if __name__ == "__main__": __main__() |
