pear.py 1.81 KB
Newer Older
1 2 3 4 5 6 7
from os import listdir, path, makedirs
from os.path import isfile, join
import sys
import shutil
import gzip
import subprocess
import argparse
8
import shlex
marc's avatar
marc committed
9
import os
10

11
parser = argparse.ArgumentParser(description='Use PEAR read merger to make a new fastq file and keep unmerged reads')
12 13 14 15 16 17

parser.add_argument("file_R1", help="reverse read file")
parser.add_argument("file_R2", help="forward read file")
parser.add_argument("output_file", help="output file")
parser.add_argument("-r1", "--keep_r1", help="keep unmerged reverse reads", action="store_true")
parser.add_argument("-r2", "--keep_r2", help="keep unmerged forward reads", action="store_true")
18
parser.add_argument("-p", "--pear-options", help="additional options passed to PEAR", default="")
19
parser.add_argument("-k", "--keep", help="keep temporary files (may take lots of disk space in the end)", action = 'store_true')
20 21 22 23 24 25 26 27


args = parser.parse_args()
f_r1 = args.file_R1
f_r2 = args.file_R2
f_out = args.output_file


28
exit_code = subprocess.call(["pear",
29 30 31
 "-f", f_r1,
 "-r", f_r2,
 "-o", f_out,
32 33 34
 "-j", "1"]
                + shlex.split(args.pear_options)
)
35

36 37
if exit_code > 0:
    raise EnvironmentError "Pear failed"
38

marc's avatar
marc committed
39 40 41 42 43 44 45 46 47 48
try :
    with gzip.open(f_out, 'w') as outFile:
        with open(f_out+'.assembled.fastq', 'rb') as f1:
            shutil.copyfileobj(f1, outFile)
        if (args.keep_r1):
            with open(f_out+'.unassembled.reverse.fastq', 'rb') as f2:
                shutil.copyfileobj(f2, outFile)
        if (args.keep_r2):
            with open(f_out+'.unassembled.forward.fastq', 'rb') as f3:
                shutil.copyfileobj(f3, outFile)
49 50 51 52
        if not args.keep:
            os.remove(f_out+'.assembled.fastq')
            os.remove(f_out+'.unassembled.reverse.fastq')
            os.remove(f_out+'.unassembled.forward.fastq')
marc's avatar
marc committed
53 54
except IOError :
    os.remove(f_out)
55
    raise