繁体   English   中英

使用python`subprocess`时,如何在参数中使用进程号?

[英]When using python `subprocess`, how can I use process number in arguments?

目前,我正在使用subprocess并行运行多个脚本,如下所示。 max_proc似乎控制着我想要多少个处理器。 以下是最少的代码。

import os
import subprocess

def main():
    args = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    max_proc = 4
    processes = set()
    for arg in args:
        cmd = ['python', '-i', arg]
        processes.add(subprocess.Popen(cmd))
        if len(processes) >= max_proc:
            os.wait()
            processes.difference_update(
                [p for p in processes if p.poll() is not None])

    # Check if all the child processes were closed
    for p in processes:
        if p.poll() is None:
            p.wait()

main()

在上面运行将类似于:

# python -i a
# python -i b
# .. and so on

在这里,如果我想在参数中包含process-number (可能从1到max_proc ),如何修改此代码? 例如

# python -i a1
# python -i b2
# python -i c3
# python -i d4
# python -i e2
# python -i f1
# python -i h3
# python -i g4
# .. and so on

为此,我必须跟踪已分配并完成的process-number (因此可以重新分配)。 有没有简单的方法?

*简而言之,我最多希望四个进程并行运行。 我还需要在参数中包含process-number (1〜4,如果从零开始,则为0〜3)。 能否请你帮忙? *

如果每个并行进程都有一个实际线程,则该线程可以将为其分配的编号视为其状态的一部分,并只需不断从共享队列中拉出输入项并按顺序处理它们即可。

例如(用实际程序替换echo ):

import os, subprocess, threading

program_to_call = 'echo' ## change this

def run(items, num):
    try:
        while True:
            item = items.pop()
            subprocess.call([program_to_call, str(num), str(item)])
    except IndexError:
        return  ## "items" is empty

def main():
    queue = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    max_proc = 4
    threads = []

    # start all four threads, passing each a different "num" and a reference to the queue
    for num in range(max_proc):
        thread = threading.Thread(target=run, args=(queue, num))
        thread.start()
        threads.append(thread)

    # wait for all four threads to finish
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM