John Doe John Doe - 6 months ago 37
Python Question

Capture dynamic command prompt output in text file

I am running a python script which checks for the modifications of files in a folder. I want that output to be printed in a file. The problem is that the output is DYNAMIC , the cmd is always open and when a file is modified, I will have an information right-ahead about that in the cmd window. All the solutions which I found were matching the situations were I just run a command and I finish with that.

I tryed with:

python > d:\output.txt

but the
file is empty

An example of the command prompt windows, after I run the command
and I touch the 2 files, the command prompt will look like this. I want to capture that output.
enter image description here


The issue is output buffering. If you wait long enough, you'll eventually see data show up in the file in "blocks". There are a few ways around it, for example:

  • Run python with the -u (unbuffered) flag
  • Add a sys.stdout.flush() after all print statements (which can be simplified by replacing stdout with a custom class to do it for you; see the linked question for more)
  • Add flush=True option to print statements if your version of Python supports it
  • If appropriate, use the logging module instead of print statements.