Here is my attempt:

    def remove_too_long_reads(bam):
    
        for read in bam:
            if read.end - read.start < 60:
                yield read

    bam = BedTool(input.bam)
    bam = BedTool(remove_too_long_reads(bam))

But when I try to use the bam file afterwards like so:

    bam.intersect(...

I get an error:

> <class 'BrokenPipeError'>: Broken pipe The command was:
> 
>         bedtools intersect -b data/gencode_annotation/tss.bed -a stdin
> 
> Things to check: Error in job intersect_data_tss while creating output
> file data/tss/bam/Exp2_9h_PolII.bam. RuleException: KeyError in line
> 31 of
> /local/home/endrebak/code/programmable_epigenetics/rules/tss/intersect_bam_gencode.rules:
> 32   File
> "/local/home/endrebak/code/programmable_epigenetics/rules/tss/intersect_bam_gencode.rules",
> line 31, in __rule_intersect_data_tss   File
> "/local/home/endrebak/anaconda3/lib/python3.5/site-packages/pybedtools/bedtool.py",
> line 773, in decorated   File
> "/local/home/endrebak/anaconda3/lib/python3.5/site-packages/pybedtools/bedtool.py",
> line 336, in wrapped   File
> "/local/home/endrebak/anaconda3/lib/python3.5/site-packages/pybedtools/helpers.py",
> line 373, in call_bedtools
I have this function in one my scripts - maybe it will help:

```

from pybedtools import BedTool

def filterReadsByLength(inbam, minlength, maxlength):
    '''
    Takes BedTool which is a bam, and selects intervals that are within the defined lengths.
    Input: bam file and min/max lengths
    Output: bedTool
    '''
    print 'Filtering reads by length'
    # convert bam to bed
    intervals = inbam.bam_to_bed()
    filt = intervals.filter(lambda x: len(x) > minlength and len(x) < maxlength).saveas()
    return filt

inbam = BedTool(path_to_bam)
filtered = filterReadsByLength(inbam, minlength, maxlength)

```

