Python - 并行运行多个OS命令,使用超时并检查返回码

时间:2014-06-25 17:45:52

标签: python python-2.7

在linux / solaris上使用python 2.7,我需要并行生成几个OS命令;如果线程/命令花费的时间超过提供的超时,它将终止命令。我一直试图用线程做这个,但是无法获得返回码。

我正在运行的命令是一个简单的dd命令,用于挂载NFS的文件系统。如果此dd命令超时,我需要获取失败的挂载点的名称并将其存储以供日后使用。我不一定需要dd命令的返回码,但想收集输出。 (我的下一个项目是需要dd输出的延迟工具)

这是我的伪代码:

<spawn several threads with each one running an OS command>

<after my timeout window, loop thru any remaining active threads and terminate them, or terminate the os command that thread is running>

<gather a list of threads (actually the mountpoint that I provided the thread), that timed out and save for later>

我是否正确行事,或者是否有更合适的方法。

许多帮助。

1 个答案:

答案 0 :(得分:0)

不确定。像这样:

task_inputs = [
        'input1',
        'input2',
        ]

class Task(object):
    def __init__(self, task_input):
        self.task_input = task_input
    def __call__(self):
        """Do your thing..."""

task_threads = []
for task_input in task_inputs:
    task = Task(task_input)
    thr = Thread(target=task)
    thr.start()
    task_threads.append((thr, task))

# wait for timeout

naughty_tasks = []
for thr, task in task_threads:
    if thr.is_alive():
        # still running!
        """Do your termination thing..."""
        naughty_tasks.append(task)


# now you have a list of Task object with their original input ( naughty_tasks[i].task_input )