-1

I am writing a function of a class to convert a sam file to bam file, then sort it and index it in python (I know it is easy to fulfill in bash, but it does not hurt to learn more).

A sam file has already been generated in the defined directory (cwd) by another function of the class already.

Here is the code:

def sam2bam(self):
    """
    return a sorted and index bam file in the working directory
    """


    if str(self.fq)[7:9] == '24':
        # create bam
        comnd = "samtools view -bS " + str(self.fq)[0:10] + ".sam > " + str(self.fq)[0:10]  + ".bam"

        print("Converting sam to bam ... (executed command: {})\n".format(comnd))
        comnd_input  = shlex.split(comnd)

        with open((str(self.fq)[0:10] + '.bam'), 'w') as f:
            Popen(comnd_input, stdout = f, stderr = PIPE, cwd = 'G24/' + str(self.fq))


        # sort bam      
        comnd2 = "samtools sort " + str(self.fq)[0:10]  + ".bam -o " + str(self.fq)[0:10]  + ".sorted.bam"  
        print('Sorting bam ... (executed command: {}\n)'.format(comnd2))

        comnd_input2  = shlex.split(comnd2)
        with open((str(self.fq)[0:10] + 'sorted.bam'), 'w') as f_sort:
            Popen(comnd_input2, stdout = f_sort, stderr = PIPE, cwd = 'G24/' + str(self.fq))

        # index bam
        comnd3 = "samtools index " + str(self.fq)[0:10]   + ".sorted.bam"   
        print('Indexing bam ... (executed command: {}\n)'.format(comnd3))

        comnd_input3  = shlex.split(comnd3)

        with open((str(self.fq)[0:10] + 'sorted.bam'), 'w') as f_index:
            Popen(comnd_input3, stdout = f_index, stderr = PIPE, cwd = 'G24/' + str(self.fq))

But nothing came out

I tried:

Popen(comnd_input, stdout = PIPE, stderr = PIPE, cwd = 'G24/' + str(self.fq))

yet nothing either. Tried save it as a variable and do .communicate(), nothing.

So I don't know what wrong I did?

thanks,

Xp

Xp.L
  • 837
  • 1
  • 7
  • 13

1 Answers1

0

refer to here.

It is because of the '>' redirecting. I modified the code to:

Popen(comnd, stdout = PIPE, stderr = PIPE, shell = True, cwd = 'G14/' + str(self.fq))

And it worked.

Xp.L
  • 837
  • 1
  • 7
  • 13