[Tutor] need help writing subprocess output to file(s)
Mats Wichmann
mats at wichmann.us
Tue Apr 28 15:42:51 EDT 2020
On 4/26/20 7:46 PM, Matthew Herzog wrote:
> Hi all.
> I have to run a utility (sdptool) that checks the firmware versions on >500
> servers.
> What I pasted below works but the stdout needs to be written to a file, one
> per IP address.
> How do I capture the stdout to files? Even a single logfile would work.
> Thanks.
>
> #!/usr/bin/python3
> import subprocess
>
> with open("ips.txt") as ip_list:
> ips = ip_list.readlines()
>
> for ip in ips:
> output = subprocess.Popen(["/opt/bin/sdptool", ip, "check"])
you really need to do something to let the above "finish" (with Popen,
that's usually a wait() or a communicate() )
you've gotten other answers, here's some of how I'd attack it which is
probably less efficient than just sending stdout directly to the file in
the subprocess call...
with open("log", "a") as f:
for ip in ips:
cp = subprocess.run(["/opt/bin/sdptool", ip, "check"],
stdout=subprocess.PIPE)
if cp.returncode:
continue # do something if it failed
f.write(cp.stdout)
More information about the Tutor
mailing list