code: def bam_to_fastq_pair(in_file, target_region, pair):
      
      space, start, end = target_region
      bam_file = pysam.Samfile(in_file, "rb")
      for read in bam_file:
          if (not read.is_unmapped and not read.mate_is_unmapped
                  and bam_file.getrname(read.tid) == space
                  and bam_file.getrname(read.mrnm) == space
                  and read.pos >= start and read.pos <= end
                  and read.mpos >= start and read.mpos <= end
                  and not read.is_secondary
                  and read.is_paired and getattr(read, "is_read%s" % pair)):
              seq = Seq.Seq(read.seq)
              qual = list(read.qual)
              if read.is_reverse:
                  seq = seq.reverse_complement()
                  qual.reverse()
              yield read.qname, str(seq), "".join(qual)
docs: Generator to convert BAM files into name, seq, qual in a region.