使用subprocess.call对整个文件目录进行多处理

时间:2016-01-30 06:51:39

标签: python-3.x subprocess python-multiprocessing

我有一个Python3脚本,使用subprocess.call在目录中的大约2,300个输入文件上运行程序,每个输入文件有两个输出文件。我有这两个输出进入两个不同的目录。我想学习如何对我的脚本进行多处理,以便同时处理多个文件。我一直在阅读Python中的多进程库,但它可能太高级,我不能理解。如果专家有任何意见,下面是脚本。非常感谢!

脚本:

import os
import subprocess
import argparse


parser = argparse.ArgumentParser(description="This script aligns DNA sequences in files in a given directory.")
parser.add_argument('--root', default="/shared/testing_macse/", help="PATH to the input directory containing CDS orthogroup files.")
parser.add_argument('--align_NT_dir', default="/shared/testing_macse/NT_aligned/", help="PATH to the output directory for NT aligned CDS orthogroup files.")
parser.add_argument('--align_AA_dir', default="/shared/testing_macse/AA_aligned/", help="PATH to the output directory for AA aligned CDS orthogroup files.")
args = parser.parse_args()


def runMACSE(input_file, NT_output_file, AA_output_file):
    MACSE_command = "java -jar ~/bin/MACSE/macse_v1.01b.jar "
    MACSE_command += "-prog alignSequences "
    MACSE_command += "-seq {0} -out_NT {1} -out_AA {2}".format(input_file, NT_output_file, AA_output_file)
    # print(MACSE_command)
    subprocess.call(MACSE_command, shell=True)

Orig_file_dir = args.root
NT_align_file_dir = args.align_NT_dir
AA_align_file_dir = args.align_AA_dir

try:
    os.makedirs(NT_align_file_dir)
    os.makedirs(AA_align_file_dir)
except FileExistsError as e:
    print(e)

for currentFile in os.listdir(args.root):
    if currentFile.endswith(".fa"):
        runMACSE(args.root + currentFile, args.align_NT_dir + currentFile[:-3]+"_NT_aligned.fa", args.align_AA_dir +   currentFile[:-3]+"_AA_aligned.fa")

1 个答案:

答案 0 :(得分:0)

子流程函数在单独的进程中运行任何命令行可执行文件。你正在运行java。多处理在单独的进程中运行python代码,就像线程在单独的线程中运行python代码一样。这两者的API有意相似。因此,多处理不能替代非python子进程调用。

使用多个python进程启动多个java进程将浪费进程。您也可以使用多个线程进行多个子进程调用。或者使用异步模块。

或制作自己的日程安排程序。在生成器函数中包含for-if。

def fa_file(path):
    for currentFile in os.listdir(path):
        if currentFile.endswith(".fa"):
            yield currentFile
fafiles = fa_file(arg.root)

制作10个Popen对象的数组。睡一段合适的间隔。唤醒后,循环遍历数组并替换完成的子进程(.poll()返回除None之外的其他内容),只要next(fafiles)返回一些东西。

编辑:如果您在Python代码中执行了调用已编译C代码(例如,枕头)的图像处理,那么您可以使用多处理和加载文件的队列来处理。

相关问题