我对 Python 很陌生,并且我编写了一个(可能非常难看的)脚本,该脚本应该从 fastq 文件中随机选择一个序列子集。fastq 文件将信息存储在每块四行的块中。每个块中的第一行以字符“@”开头。我用作输入文件的 fastq 文件为 36 GB,包含大约 14,000,000 行。
我试图重写一个已经存在的使用太多内存的脚本,并且我设法减少了很多内存使用量。但是脚本需要永远运行,我不明白为什么。
parser = argparse.ArgumentParser()
parser.add_argument("infile", type = str, help = "The name of the fastq input file.", default = sys.stdin)
parser.add_argument("outputfile", type = str, help = "Name of the output file.")
parser.add_argument("-n", help="Number of sequences to sample", default=1)
args = parser.parse_args()
def sample():
linesamples = []
infile = open(args.infile, 'r')
outputfile = open(args.outputfile, 'w')
# count the number of fastq "chunks" in the input file:
seqs = subprocess.check_output(["grep", "-c", "@", str(args.infile)])
# randomly select n fastq "chunks":
seqsamples = random.sample(xrange(0,int(seqs)), int(args.n))
# make a list of the lines that are to be fetched from the fastq file:
for i in seqsamples:
linesamples.append(int(4*i+0))
linesamples.append(int(4*i+1))
linesamples.append(int(4*i+2))
linesamples.append(int(4*i+3))
# fetch lines from input file and write them to output file.
for i, line in enumerate(infile):
if i in linesamples:
outputfile.write(line)
grep 步骤几乎不需要任何时间,但 500 多分钟后,脚本仍未开始写入输出文件。所以我想这是 grep 和最后一个 for 循环之间的步骤之一,需要这么长时间。但我不明白究竟是哪一步,以及我能做些什么来加快它。