if STREAM.isatty():
Peter Otten
__peter__ at web.de
Thu Aug 29 19:29:48 EDT 2019
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?
Perhaps a simple example can help?
$ cat checktty.py
import sys
stream = sys.stdout
if stream.isatty():
message = "tty"
else:
message = "no tty"
print(message, file=stream)
When you run the script it prints to the terminal:
$ python3 checktty.py
tty
But when you redirect to a pipe or into a file:
$ python3 checktty.py | cat
no tty
$ python3 checktty.py > tmp.txt
$ cat tmp.txt
no tty
More information about the Python-list
mailing list