Query regarding sys.stdout.write
Cameron Simpson
cs at zip.com.au
Sun Jun 7 18:40:42 EDT 2015
On 08Jun2015 02:47, Sreenath Nair <sreenath.cg at gmail.com> wrote:
>I have a general query about the following snippet:
>
>import os
>Import sys
>for each_dir in os.listdir("/home/tmpuser"):
> full_path = os.path.join("/home/tmpuser", each_dir)
> sys.stdout.write("\r%s" % full_path)
> sys.stdout.flush()
>
>The snippet is a simplified example of me trying to print to the same line by using carriage return. This is working fine. However, the issue is that if the previous line was longer than the current line being printed then there are characters leftover from the previous print. Like so:
>
>Print no. 1: /home/tmpuser/somedir/somefile.ext
>Print no. 2:/home/tmpuser/somefile.extmefile.ext
>
>In case of the newly printed shorter line, the characters from the previously printed longer line are leftover... Is there any way to clear the previous print? While still being able to print to the same line?
Certainly. Keep track of the length of the previous line. Pad the new line with
sufficient spaces to overwrite the old line, and then sufficient backspaces to
get back to the end of the new line.
For added points, write a minimal updated that notices if the old line had a
common prefix with the new line, and emit only the change.
Cheers,
Cameron Simpson <cs at zip.com.au>
The worst tyrannies were the ones where a governance required its own logic on
every embedded node. - Vernor Vinge
More information about the Python-list
mailing list