1

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())
Eyal S
  • 63
  • 11
  • Take a look at this question https://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running – timlyo Nov 14 '16 at 12:26

1 Answers1

1

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)
Billy
  • 5,179
  • 2
  • 27
  • 53
Justin
  • 66
  • 4