On 29/08/2019 04:40, Hongyi Zhao wrote:
Hi,
I read the following code:
https://github.com/shichao-an/homura/blob/master/homura.py
On the line 265-266, it said:
if STREAM.isatty():
p = (self.progress_template + '\r') % params
What's mean by using the above two lines? Can I not use them?
If you don't understand them, you definitely shouldn't use them. So
let's fix that :-)
"isatty()" is a method of the io.IOBase class that checks to see if the
stream is connected to a tty, or to use less jargon, if it is
interactive. "tty" was I think originally an abbreviation for
"teletype", but nowadays it refers to any terminal, anywhere you get a
command line prompt. See
https://docs.python.org/3/library/io.html#io.IOBase.isatty
The next line gives you a cheap and cheerful progress message. I
haven't looked at the rest of the code, but I imagine
"self.progress_template" gets set somewhere with a string rather like
"%d%% complete". What the expression does is add a carriage return
character to the end of the string (but *not* a line feed -- remember
that, it will be important in a minute), then the % operator formats the
string (see
https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)
using the information in "params".
This is easiest to show by example. Suppose "self.progress_template" is
"%d%% complete" as I suggested, and "params" is 1. Then "p" becomes the
string "1% complete\r" (where \r is the carriage return character).
Presumably a little later the code does
STREAM.write(p)
which will write "1% complete" to the terminal and then put the cursor
(the "writing point") back to the start of the line. Since there is no
carriage return character, it does *not* move on to a new line. The
next time we call this code, say with params = 2, we write out "2%
complete" over the top of the previous message, obliterating the old
text. The cursor is once again at the start of the line, so we can
carry on with "3% complete", "4% complete" and so on.
TLDR: these two lines set up (but don't output) a progress message for
an interactive stream.
--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list