1 from csamtools import *
6 class SamtoolsError( Exception ):
7 '''exception raised in case of an error incurred in the samtools library.'''
9 def __init__(self, value):
12 return repr(self.value)
14 class SamtoolsDispatcher(object):
15 '''samtools dispatcher.
17 Emulates the samtools command line as module calls.
19 Captures stdout and stderr.
21 Raises a :class:`pysam.SamtoolsError` exception in case
22 samtools exits with an error code other than 0.
24 Some command line options are associated with parsers.
25 For example, the samtools command "pileup -c" creates
26 a tab-separated table on standard output. In order to
27 associate parsers with options, an optional list of
28 parsers can be supplied. The list will be processed
29 in order checking for the presence of each option.
31 If no parser is given or no appropriate parser is found,
32 the stdout output of samtools commands will be returned.
37 def __init__(self,dispatch, parsers):
38 self.dispatch = dispatch
39 self.parsers = parsers
42 def __call__(self,*args, **kwargs):
43 '''execute the samtools command
45 retval, stderr, stdout = csamtools._samtools_dispatch( self.dispatch, args )
46 if retval: raise SamtoolsError( "\n".join( stderr ) )
48 # samtools commands do not propagate the return code correctly.
49 # I have thus added this patch to throw if there is output on stderr.
50 # Note that there is sometimes output on stderr that is not an error,
51 # for example: [sam_header_read2] 2 sequences loaded.
52 # Ignore messages like these
53 stderr = [ x for x in stderr if not x.startswith( "[sam_header_read2]" ) ]
54 if stderr: raise SamtoolsError( "\n".join( stderr ) )
56 # call parser for stdout:
57 if not kwargs.get("raw") and stdout and self.parsers:
58 for options, parser in self.parsers:
59 for option in options:
60 if option not in args: break
66 def getMessages( self ):
70 '''return the samtools usage information for this command'''
71 retval, stderr, stdout = csamtools._samtools_dispatch( self.dispatch )
72 return "".join(stderr)
75 # samtools command line options to export in python
77 # import is a python reserved word.
79 "view" : ( "view", None ),
80 "sort" : ( "sort", None),
81 "samimport": ( "import", None),
82 "pileup" : ( "pileup", ( (("-c",), Pileup.iterate ), ), ),
83 "faidx" : ("faidx", None),
84 "tview" : ("tview", None),
85 "index" : ("index", None),
86 "fixmate" : ("fixmate", None),
87 "glfview" : ("glfview", None),
88 "flagstat" : ("flagstat", None),
89 "calmd" : ("calmd", None),
90 "merge" : ("merge", None),
91 "rmdup" : ("rmdup", None) }
93 # instantiate samtools commands as python functions
94 for key, options in SAMTOOLS_DISPATCH.iteritems():
96 globals()[key] = SamtoolsDispatcher(cmd, parser)
98 # hack to export all the symbols from csamtools
99 __all__ = csamtools.__all__ + [ "SamtoolsError", "SamtoolsDispatcher" ] + list(SAMTOOLS_DISPATCH) +\