格式化输出 - python

时间:2012-01-06 17:26:04

标签: python

我这里有这段代码

import subprocess
from time import strftime       # Load just the strftime Module from Time

f = open('check_'+strftime("%Y-%m-%d")+'.log', 'w')
for server in open('check.txt'):
    f.write(server.strip() + "\n")
    subprocess.Popen(['plink', server.strip(), 'df','-k'],stdout=f)

我想要的是输出,所以它显示:

  

服务器名称

     

输出

     

服务器名称

     

输出

目前显示:

  

服务器名称

     

服务器名称

     

输出

     

输出

提前致谢

1 个答案:

答案 0 :(得分:2)

首先 - 如果您打算在远程服务器中运行不同的命令,请查看Fabric

默认情况下,subprocess.Popen在后台运行,您的命令可能比循环中的其他内容慢得多(比如打印服务器名称)。试试这个以迫使它等待每个过程:

import subprocess
from time import strftime       # Load just the strftime Module from Time

f = open('check_'+strftime("%Y-%m-%d")+'.log', 'w')
for server in open('check.txt'):
    f.write(server.strip() + "\n")
    p = subprocess.Popen(['plink', server.strip(), 'df','-k'],stdout=f)
    p.wait()
    f.flush()

如果打算使进程并行运行,我只需将每个服务器日志写入另一个文件。然后在需要时连接结果。