[英]Why usage of end argument of print function changing the output time?
Maybe I wrote smth strange in a question title, I'l try to explain. 也许我在问题标题中写了一些奇怪的内容,我会尝试解释一下。
I'm trying to do password input as in linux-based systems (no symbols shows while you type). 我正在尝试像在基于linux的系统中那样输入密码(键入时不显示任何符号)。
I found one function that did it. 我发现有一个功能可以做到这一点。
def getchar():
import tty, termios, sys
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
pwd = ''
print('Type password:', end=' ') # HERE IS THE PROBLEM
while True:
ch = getchar()
if ch == '\r':
break
pwd += ch
print(pwd)
If I do not use end
argument it looks like that: 如果我不使用
end
参数,它看起来像这样:
But with end
argument: 但是带有
end
参数:
Line 'Type password:' will appear after while
loop end. while
循环结束后将出现“输入密码:”行。 Why is this and what can I do? 为什么会这样,我该怎么办?
By default, sys.stdout
is line buffered , which means that anything written to it is buffered up until a newline is seen. 默认情况下,
sys.stdout
是行缓冲的 ,这意味着写入其中的所有内容都会被缓冲直到看到换行符为止。
Because you replaced the standard end='\\n'
with a space, no newline is seen yet and the buffer is not flushed. 因为您用空格替换了标准
end='\\n'
,所以看不到换行符,也不会刷新缓冲区。 Set flush=True
to force a buffer flush anyway : 设置
flush=True
仍然强制刷新缓冲区:
print('Type password:', end=' ', flush=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.