code: def convert_bam_to_bed(in_bam, out_file):
      
      with file_transaction(out_file) as tx_out_file:
          with open(tx_out_file, "w") as out_handle:
              subprocess.check_call(["bamToBed", "-i", in_bam, "-tag", "NM"],
                                    stdout=out_handle)
      return out_file
docs: Convert BAM to bed file using BEDTools.