【发布时间】: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 对象的输入?
【问题讨论】:
-
不相关:您的
run_in_parallel()不正确(不要在迭代期间从序列中删除项目;usebreakinstead)。 A simple way to keep the same number of parallel process is to use a thread pool -
谢谢,我去看看。
标签: python-2.7 subprocess