root/galaxy-central/tools/samtools/bam_to_sam.py

リビジョン 2, 2.4 KB (コミッタ: hatakeyama, 14 年 前)

import galaxy-central

行番号 
1#!/usr/bin/env python
2"""
3Converts BAM data to sorted SAM data.
4usage: bam_to_sam.py [options]
5   --input1: SAM file to be converted
6   --output1: output dataset in bam format
7"""
8
9import optparse, os, sys, subprocess, tempfile, shutil
10from galaxy import eggs
11import pkg_resources; pkg_resources.require( "bx-python" )
12from bx.cookbook import doc_optparse
13#from galaxy import util
14
15def stop_err( msg ):
16    sys.stderr.write( '%s\n' % msg )
17    sys.exit()
18
19def __main__():
20    #Parse Command Line
21    parser = optparse.OptionParser()
22    parser.add_option( '', '--input1', dest='input1', help='The input SAM dataset' )
23    parser.add_option( '', '--output1', dest='output1', help='The output BAM dataset' )
24    ( options, args ) = parser.parse_args()
25
26    tmp_dir = tempfile.mkdtemp()
27    try:
28        # exit if input file empty
29        if os.path.getsize( options.input1 ) == 0:
30            raise Exception, 'Initial BAM file empty'
31        # Extract all alignments from the input BAM file to SAM format ( since no region is specified, all the alignments will be extracted ).
32        command = 'samtools view -o %s %s' % ( options.output1, options.input1 )
33        tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name
34        tmp_stderr = open( tmp, 'wb' )
35        proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() )
36        returncode = proc.wait()
37        tmp_stderr.close()
38        # get stderr, allowing for case where it's very large
39        tmp_stderr = open( tmp, 'rb' )
40        stderr = ''
41        buffsize = 1048576
42        try:
43            while True:
44                stderr += tmp_stderr.read( buffsize )
45                if not stderr or len( stderr ) % buffsize != 0:
46                    break
47        except OverflowError:
48            pass
49        tmp_stderr.close()
50        if returncode != 0:
51            raise Exception, stderr
52    except Exception, e:
53        #clean up temp files
54        if os.path.exists( tmp_dir ):
55            shutil.rmtree( tmp_dir )
56        stop_err( 'Error extracting alignments from (%s), %s' % ( options.input1, str( e ) ) )
57    #clean up temp files
58    if os.path.exists( tmp_dir ):
59        shutil.rmtree( tmp_dir )
60    # check that there are results in the output file
61    if os.path.getsize( options.output1 ) > 0:
62        sys.stdout.write( 'BAM file converted to SAM' )
63    else:
64        stop_err( 'The output file is empty, there may be an error with your input file.' )
65
66if __name__=="__main__": __main__()
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。