Python3:将"select.select"与print(str, end=)一起使用



我使用select.select()而不是输入,因为我希望输入超时。我在print()函数中使用"end"参数,因为我希望我的终端有这样一行:

键入在此处键入内容

相反,直到我键入一个字符串并按enter键之后,我才会看到"Type>"。

我的代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Made by Devyn Collier Johnson, NCLA, Linux+, LPIC-1, DCTS
import sys, select
print('Type > ', end=" ")
INPUT, VOID0, VOID1 = select.select([sys.stdin], [], [], 3)
if (INPUT):
    print('You said, ' + sys.stdin.readline().strip())
else:
    print('You said nothing!')

我使用这个脚本来测试select.select()和print(str,end=")。我阅读了这篇文章(如何在print语句后取消换行?)和这两个命令的官方Python3文档。

stdout默认情况下是缓冲的,要强制显示它,您需要刷新它:

print('Type > ', end='')
sys.stdout.flush()

注意,print也通过关键字参数支持这一点:

print('Type > ', end='', flush=True)

最新更新