简体   繁体   中英

Format the output - python

I have this code here

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)

What I would like to have is the output so it shows:

Server Name

Output

Server Name

Output

Currently it shows:

server name

server name

output

output

Thanks in advance

First of all - if your intention is to run different commands in remote servers, take a look at Fabric .

By default subprocess.Popen runs in the background, and your command is probably much slower than the other things in your loop (like printing the server names). Try this to force it to wait for each process:

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()

If you intend to make the process run in parallel, I'd just write each server log to a different file. Then concatenate the result if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM