Query regarding sys.stdout.write

Cameron Simpson cs at zip.com.au
Sun Jun 7 21:56:25 EDT 2015


On 08Jun2015 10:18, Chris Angelico <rosuav at gmail.com> wrote:
>On Mon, Jun 8, 2015 at 7:17 AM, 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?
>
>The most common solution is to print out some spaces to overwrite the
>previous text. It's simple, straight-forward, and works on all
>systems. But if your console is properly ANSI-compliant, you may be
>able to simply append \33[K to clear to end of line:

If you want do do this version portably, hook into the Python curses module and 
get the result of curses.tigetstr('el'). If that returns None, the terminal 
does not support clear-to-end-of-line and you should use the spaces-overwrite 
technique. But if it returns a string, you can write that string, whatever it 
is, to erase to the end of the line.

Most modern terminals are ANSI supersets, but the terminfo database has a huge 
suite of descriptions of terminals, and this will get your the right sequence, 
whatever that may be, for your current terminal.

Of course, reaching for the curses module is massive overkill in a sense, but 
it is the only way to consult terminfo in the Python stdlib.

See "man terminfo" for details on what terminal capabilities the terminfo 
database describes.

Cheers,
Cameron Simpson <cs at zip.com.au>

But I have to say, I "non-concur." (Non-concur was a term I learned at
IBM. IBM seemed to be a breeding ground for making up words and
phrases, turning verbs into nouns, etc. "Non-concur" seems to be for
those times when saying "I disagree" just isn't strong enough!)
        - Robert D. Seidman <robert at clark.net>



More information about the Python-list mailing list