简体   繁体   English

为什么使用print函数的end参数改变输出时间?

[英]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.

相关问题 如何在打印 function 中使用“end”关键字参数? - How to use 'end' keyword argument with print function? 打印函数中“结束”参数的作用是什么? - What is the job of the "end" argument in the print function? 为什么在 Python 的打印函数中传递给关键字参数 end 的参数没有在下面的上下文中按预期工作? - Why does not the parameter passed to the keyword argument end in the print function of Python does not work as expected in the below context? 打印的end参数导致time.sleep的行为不同 - end argument to print leads to different behavior with time.sleep 为什么打印 function 最后会留一个空格? - Why does the print function leave a space at the end? 将结束参数与打印函数一起使用时的 Python SyntaxError - Python SyntaxError when using end argument with print function 误解 end= 参数如何在 print() function 在 while 循环中工作 - Misunderstanding how end= argument works in print() function in a while loop 不能在 Print() function 的 Else 语句中使用 End 参数 - Cannot use End argument within Else statement in Print() function 为什么有些 output 的打印 function 是 2 行,而另一些是 1? - Why is some output of the print function 2 lines and others 1? 为什么这个 function 没有返回 output 并且只使用打印? - Why is this function returning no output and only working with print?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM