code: def get_minibam_bed(bamfile, bedfile, minibam=None):
      
      pf = op.basename(bedfile).split(".")[0]
      minibamfile = minibam or op.basename(bamfile).replace(".bam", ".{}.bam".format(pf))
      minisamfile = minibam.replace(".bam", ".sam")
      baifile = minibamfile + ".bai"
      if op.exists(baifile):
          sh("rm {}".format(baifile))
  
      cmd = "samtools view -H {} > {}".format(bamfile, minisamfile)
      sh(cmd)
  
      cmd = "cat {}".format(bedfile)
      cmd += " | perl -lane 'print \"$F[0]:$F[1]-$F[2]\"'"
      cmd += " | xargs -n1 -t -I \{\}"
      cmd += " samtools view {}".format(bamfile)
      cmd += " \{\} >> " + minisamfile
      sh(cmd)
  
      cmd = "samtools view {} -b".format(minisamfile)
      cmd += " | samtools sort -"
      cmd += " -o {0}".format(minibamfile)
  
      sh(cmd)
      sh("samtools index {0}".format(minibamfile))
      return minibamfile
docs: samtools view -L could do the work, but it is NOT random access. Here we
      are processing multiple regions sequentially. See also:
  
      https://www.biostars.org/p/49306/