【问题标题】:Getting input given to subprocess.Popen from stored subprocess.Popen object从存储的 subprocess.Popen 对象获取给 subprocess.Popen 的输入
【发布时间】:2015-12-18 16:17:20
【问题描述】:

如果我有一个subprocess.Popen 对象的列表,有没有办法知道在生成它们时最初使用了什么命令?

Python 2.7

背景: 我有一个启动测试的各种命令的列表。如果其中一项测试失败,脚本会清理环境。然后我只想重试那些失败的命令。

注意:以下命令仅用于演示目的;在我的产品代码中调用的那些更复杂,但这不是重点。如果我能做到这一点,它将与我的 prod cmds 一起工作。

commands = [['nosetests', '-V'],
        ['nosetests', '--collect-only'],
        ['nosetests', '--with-id']
        ]

def cleanup_env():
    ...do things...

def run_in_parallel(cmds, retry):
    retry_tasks = []

    if not cmds:
        return

    def done(p):
        return p.poll() is not None

    def success(p):
        return p.returncode == 0

    def fail(p):
        if not retry:
            retry_tasks.append(p)
            print("{} failed, will need to retry.".format(retry_tasks))
        else:
            pass # if this is already a retry, we don't care, not going to retry again

    MAX_PARALLEL = 4
    processes = []

    while True:
        while cmds and len(processes) < MAX_PARALLEL:
            task = cmds.pop() # pop last cmd off the stack
            processes.append(subprocess.Popen(task))

        for p in processes:
            if done(p):
                if success(p):
                    processes.remove(p)
                else:
                    fail(p)
                    processes.remove(p)

        if not processes and not cmds:
            break

        else:
            time.sleep(0.05)

    return retry_tasks

调用上面的:

retry_list=run_in_parallel(commands, False)

if retry_list:
    cleanup_env()
    run_in_parallel(retry_list, True)

第一部分有效,但调用重试不是因为我传递的是 subprocess.Popen 对象列表,而不是它们的初始输入。

因此问题是,我如何获得subprocess.Popoen 对象的输入?

【问题讨论】:

标签: python-2.7 subprocess


【解决方案1】:

Python 2.7 中没有Popen.args。对于processes,您可以使用字典而不是列表,其中键是Popen 实例,值是对应的Popen 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    相关资源
    最近更新 更多