Eyal S Eyal S - 3 months ago 20
Python Question

communicating with CMD while saving response live

Is there any possible way to communicate with the

cmd
and at the same time save all its output to a file?

I mean that after every command the output will be saved, not at the end of the sub-process.

I want it to be something like this:

import subprocess
process = subprocess.Popen('C:\\Windows\\system32\\cmd.exe', stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
while True:
with open("log.txt", "a+") as myfile:
myfile.write(process.stdout.readlines())
process.stdin(raw_input())

Answer

You have two ways of doing this, either by creating an iterator from the read or readline functions and do:

     import subprocess
     import sys
     with open('test.log', 'w') as f:
     process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
     for c in iter(lambda: process.stdout.read(1), ''):
     sys.stdout.write(c)
     f.write(c)

or

     import subprocess
     import sys
     with open('test.log', 'w') as f:
     process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
     for line in iter(process.stdout.readline, ''):
     sys.stdout.write(line)
     f.write(line)