pear.py 1.89 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
parser.add_argument("pear_dir", help="path to pear executable")
14 15 16 17 18
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")
19
parser.add_argument("-p", "--pear-options", help="additional options passed to PEAR", default="")
20
parser.add_argument("-k", "--keep", help="keep temporary files (may take lots of disk space in the end)", action = 'store_true')
21 22 23 24 25 26 27 28


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


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

37
if exit_code > 0:
Mikaël Salson's avatar
Mikaël Salson committed
38
    raise EnvironmentError("Pear failed")
39

marc's avatar
marc committed
40 41 42 43 44 45 46 47 48 49
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)
50 51 52 53
        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
54 55
except IOError :
    os.remove(f_out)
56
    raise