Python wrapper -- and more -- for Aaron Quinlan's BEDTools (bioinformatics tools)
Python C++ Shell HTML
Clone or download
daler Merge pull request #240 from muppetjones/patch-1
Use `with open` in `helpers.isBGZIP`
Latest commit 9991931 Mar 14, 2018
Failed to load latest commit information.
docker reorganize helper scripts Jan 26, 2016
docs Merge branch 'master' of Sep 2, 2017
tools reorganize helper scripts Jan 26, 2016
.gitignore ignore autodocs after building Aug 27, 2015
.travis.yml disable osx testing Sep 2, 2017
LICENSE.txt ensure .cxx and .c files make it to sdist Aug 27, 2015
README.rst add bioconda install badge Nov 25, 2015 add new docs-building script Sep 3, 2015
dev-requirements.txt add dev-requirements.txt Sep 4, 2015 update Jun 16, 2015
optional-requirements.txt temporarily pin bedtools for tests Dec 20, 2017
requirements.txt add nose to requirements; deactivate env before deleting Aug 3, 2016
setup.cfg add universal wheel to setup.cfg Aug 27, 2015 set REV=10 in Sep 2, 2017
test-requirements.txt add reqs files Aug 3, 2016



The BEDTools suite of programs is widely used for genomic interval manipulation or "genome algebra". pybedtools wraps and extends BEDTools and offers feature-level manipulations from within Python.

See full online documentation, including installation instructions, at

Why pybedtools?

Here is an example to get the names of genes that are <5 kb away from intergenic SNPs:

from pybedtools import BedTool

snps = BedTool('snps.bed.gz')  # [1]
genes = BedTool('hg19.gff')    # [1]

intergenic_snps = snps.subtract(genes)                       # [2]
nearby = genes.closest(intergenic_snps, d=True, stream=True) # [2, 3]

for gene in nearby:             # [4]
    if int(gene[-1]) < 5000:    # [4]
        print         # [4]

Useful features shown here include:

  • [1] support for all BEDTools-supported formats (here gzipped BED and GFF)
  • [2] wrapping of all BEDTools programs and arguments (here, subtract and closest and passing the -d flag to closest);
  • [3] streaming results (like Unix pipes, here specified by stream=True)
  • [4] iterating over results while accessing feature data by index or by attribute access (here [-1] and .name).

In contrast, here is the same analysis using shell scripting. Note that this requires knowledge in Perl, bash, and awk. The run time is identical to the pybedtools version above:


snp_fields=`zcat $snps | awk '(NR == 2){print NF; exit;}'`
distance_field=$(($gene_fields + $snp_fields + 1))

intersectBed -a $snps -b $genes -v > $intergenic_snps

closestBed -a $genes -b $intergenic_snps -d \
| awk '($'$distance_field' < 5000){print $9;}' \
| perl -ne 'm/[ID|Name|gene_id]=(.*?);/; print "$1\n"'

rm $intergenic_snps

See the Shell script comparison in the docs for more details on this comparison, or keep reading the full documentation at