osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

if STREAM.isatty():


On 2019-08-29 23:38, Hongyi Zhao wrote:
> On Thu, 29 Aug 2019 16:42:44 +0100, Rhodri James wrote:
> 
>> I don't understand what's to not to understand.
>> 
>>    if condition:
>>      do_something_because_condition_is_true()
>>    else:
>>      do_something_because_condition_is_false()
>> 
>> is a perfectly normal construction.  If you mean something else, please
>> be explicit.
> 
> Let me say it more explicitly:
> 
> The original code snippet's logic is as follows:
> 
>          if STREAM.isatty():
>              p = (self.progress_template + '\r') % params
>          else:
>             [do something to reset the new value of p]
>             p = (self.progress_template + '\n') % params
>          STREAM.write(p)
>          STREAM.flush()
> 
> 
> In order to refresh the tty, the if and else must be run alternatively.
> i.e., the isatty() must return 0 and 1 periodically.
> 
> I still understand how the above code will let the isatty() return 0 and
> 1 in turn?
> 
No.

Either it's outputting to a TTY, or it isn't.

If it detects that it's outputting to a TTY, it'll make the progress 
messages overwrite each other on the same line. This looks better on an 
interactive terminal than printing many lines and scrolling the display.

If it detects that it's _not_ outputting to a TTY (probably a file), 
it'll write the progress messages one after another. This makes more 
sense in, say, a log file.