【问题标题】:multi threading in subprocess module of python [duplicate]python的子进程模块中的多线程[重复]
【发布时间】:2015-03-12 10:44:21
【问题描述】:

我有几台 Unix 服务器,上面运行着一个应用程序,我需要从应用程序日志中对每台服务器上的一些模式进行 grep,并将所有服务器的 grep 结果放入一个统一文件中。

这就是我目前的做法。

def run_command(command):
   ps = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
   out,err = ps.communicate()
   if err != "":
     return err
   else:
     return out



Server_List = [['ServerA','BecomeAccountA'],['ServerB','BecomeAccountB'],['ServerC','BecomeAccountC'],['ServerD','BecomeAccountD']]
Final_Result = ""
path = "some/path/"
pattern = "FindMe"
for list in Server_List:
    server= list[0]
    becomeaccount = list[1]
    command="ssh -oConnectTimeout=5 -oBatchMode=yes -l %s %s 'grep %s %s'" % (becomeaccount,server,pattern,path)
    result = run_command(command)
    Final_Result+=result

with open("/some/path/output",'w') as f:
f.write(Final_Result)

现在我的output 文件包含以下内容:

14012015.1449.30 [INFO] something FindMe something
14012015.1449.40 [INFO] something FindMe something
14012015.1450.13 [INFO] something FindMe something
14012015.1450.48 [INFO] something FindMe something
14012015.1451.04 [INFO] something FindMe something
14012015.1451.19 [INFO] something FindMe something
14012015.1451.77 [INFO] something FindMe something
14012015.1452.09 [INFO] something FindMe something

要在output 文件中得到这个结果,我必须一个接一个地与所有服务器建立 ssh 连接,这需要一些时间来处理。我需要减少代码花费的时间才能获得最终输出。我想知道我可以在多线程中做到这一点吗?我的意思是一次建立多个 ssh 连接?我从未尝试过多线程。

注意:- output 文件中的行顺序并不重要,因此 ssh 连接的顺序也不是必需的,因为我总是可以对 output 文件中的行进行排序时间,因为它在每行的开头都有时间戳。

【问题讨论】:

  • 听起来你正在做的事情可能是 io-bound,所以多线程听起来可能会有所帮助。但是,它可能完成的只是允许您并行等待所有服务器。
  • 不相关:您可以使用退出状态ps.returncode != 0 作为错误指示器。如果要检查字符串 err 是否不为空,请使用 if err 而不是 if err != "" (后者在 Python 3 上失败,其中 bytesstr 是不同的类型)并且它在 Python 上不是惯用的2个。

标签: python multithreading ssh subprocess


【解决方案1】:

我认为 ps.communicate() 会等到进程的所有输出都被读取。 这使您的程序有顺序。

正如您所提到的,最好生成线程,其中每个线程调用一个子进程并处理进程输出/错误的读取。

在收集输出时,您需要将它们放入允许并行访问的队列或列表中,例如查看队列模块。

最后,您还需要“加入”线程,即。等待所有线程终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 2017-04-12
    • 2016-06-13
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多