Is there a way to flush the stdout of pprint
on a single invocation? I know we can start the interpreter unbuffered, with e.g. python -u
, but I really just want this behavior for a one-time call.
Asked
Active
Viewed 212 times
0

flow2k
- 3,999
- 40
- 55
-
You would probably need to create your own instance of `pprint.PrettyPrinter` where you call `self._stream.flush()` when you instantiate it. – MattDMo Aug 14 '22 at 01:31
-
Can you explain more clearly what the problem is and what you want? It's not clear to me. – Kelly Bundy Aug 14 '22 at 06:40
-
@KellyBundy Are you asking about the rationale behind wanting to flush pprint's output? – flow2k Aug 17 '22 at 03:36
-
Doesn't it flush automatically anyway, due to writing newline characters? And if you know the term "flush", you probably also know (or can look up) how to flush, so (why) can't you just do that after the pprint call? – Kelly Bundy Aug 17 '22 at 08:25
-
It doesn't seem to flush automatically with the newlines (is there somewhere that explains the relationship between \n and flushing?) I recall `sys.stdout.flush()` worked for python2 but not sure about python3. Maybe it's this https://docs.python.org/3/library/io.html#io.IOBase.flush. – flow2k Aug 17 '22 at 08:39
-
1There's a bit [here](https://docs.python.org/3/library/sys.html#sys.stdout), starting at "When interactive" and including the note box. I think "line-buffered" means flush at newlines. Are you using interactive, and what Python version are you using? And what happened when you tried `sys.stdout.flush()`? – Kelly Bundy Aug 17 '22 at 09:07
-
Thanks - it was not run interactively so I guess that's why the newlines did not force the flush. I'm on Python 3, and `sys.stdout.flush()` worked! For some reason I thought that only worked in Python 2, but I must have remembered wrong. – flow2k Aug 19 '22 at 00:51
-
1Oh, I misread the docs, thought it said it's line-buffered since Python 3.9, but that's only for stderr. Anyway, I'd expect `sys.stdout.flush()` to work. If you write to disk, then maybe following it with [os.fsync](https://docs.python.org/3.10/library/os.html?highlight=fsync#os.fsync) is needed, not sure (maybe that was only true in Python 2). – Kelly Bundy Aug 19 '22 at 08:46