首页 文章

Python在map中执行subprocess.call

提问于
浏览
0

嗨,我有以下代码:

import sys
import multiprocessing as mp


def create_parser():
    from argparse import ArgumentParser, FileType
    ap = ArgumentParser()
    ap.add_argument('infile', type=FileType('r'),
        help="file with shell commands to execute")
    ap.add_argument('-n', '--ncpu', type=int, default=0,
        help="Number of CPUs to use (default: %(default)s: all CPUs)")
    return ap


def cpus_to_use(ncpu):
    return ncpu if ncpu else mp.cpu_count()


if __name__ == '__main__':
    from subprocess import call

    ap = create_parser()
    args = ap.parse_args(sys.argv[1:])

    ncpu = cpus_to_use(args.ncpu)

    if args.infile:
        # Read commands from already open file and close
        commands = [c for c in args.infile.read().split('\n') if c]
        args.infile.close()

        # Create a pool and map run_cmd to the shell commands
        pool = mp.Pool(processes=ncpu)
        pool.map(call, commands)

我基本上是从命令行导入一个文本文件,每个行都有一个特定的命令要执行(我正在尝试并行化) . 我正在使用Python 2.7.12并且print(命令)的输出看起来很好 .

我怀疑我得到的最后一行行语法中有一个错误:文件“run_parallel.py”,第47行,在pool.map(调用,命令)文件“/ home / ect / anaconda2 / lib / python2 . 7 / multiprocessing / pool.py“,第251行,在map中返回self.map_async(func,iterable,chunksize).get()文件”/home/ect/anaconda2/lib/python2.7/multiprocessing/pool.py“ ,第567行,获得提升self._value

谢谢

1 回答

  • 0
    commands = [c.split() for c in args.infile.read().split('\n') if c]
    

    (这是来自http://sburns.org/2014/05/03/cortical-tractography-recipe.html,对吧?我遇到了同样的问题:)它似乎可以通过在白色空格中分割命令中的每个条目来工作,这样池就能够正确地解析每个函数调用的参数 .

相关问题