python - 测试条件不工作

标签 python select timeout sys

我在代码中使用带有选择和系统库的Python:

from __future__ import (absolute_import, division,
                            print_function, unicode_literals)
from select import select
import sys
def main():
    timeout = 5
    print('Please type something: ', end = '')
    sys.stdout.flush()
    rlist, wlist, xlist = select([sys.stdin],[],[], timeout)
    k=sys.stdin.readline()
    if k=="f":
        data = sys.stdin.readline()
        print('you entered', data)
    else:
        print('\nSorry, {} seconds timeout expired!'.format(timeout))
        print(k) #see the sys.stdin result
if __name__ == '__main__':
    main()

这个程序等待用户直到输入一个字符 我在程序中添加了一个条件,如果用户在 5 秒后输入一个字符,那么如果用户给出与“f”字符不同的内容,程序也会停止,但问题是条件不起作用,我进行了测试以查看结果他给了我 'f 字符,但是当我将结果放入 if 语句中时,程序无法工作 结果的屏幕截图: enter image description here

有人可以告诉我这个结果的原因吗?

最佳答案

我对 select 库了解不多。但这里有一个错误立即引起了我的注意。

您可以使用k=sys.stdin.readline()读取输入。这意味着 k 将包含完整的行,包括 \n (换行符)符号。因此,如果您按 f + Enterk 的值将是 "f\n",而不是 "f" >。这就是为什么比较总是错误的原因。

最好将这些值与 if k.strip() == "f": 进行比较。

<小时/>

编辑

刚刚快速浏览了 select 库。如果要确定是否发生超时,则需要使用 select 函数的返回值。并且不直接从输入读取。否则,无论是否发生超时,您都会等待。

我不确定您想要完成什么,但类似于以下代码的内容可以工作。

from __future__ import print_function
from select import select
import sys

timeout = 5
print('Please type something: ', end = '')
sys.stdout.flush()
inputready, _, _ = select([sys.stdin],[],[], timeout)
if inputready:
    k = sys.stdin.readline()
    if k.strip()=="f":
        print("You printed 'f'")
    else:
        print("Not 'f'")
else:
    print('\nSorry, {} seconds timeout expired!'.format(timeout))

关于python - 测试条件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45255147/

相关文章:

Mongodb查询从多个键中选择记录

javascript - $timeout.cancel() 没有取消超时

python - 如何使用Python对字符串进行编码

python - SQLALchemy 动态 filter_by

C 使用 select() 从两个命名管道(FIFO)中读取

deployment - Heroku 错误 H12(请求超时)问题

c# - .NET 的 Oracle 数据提供程序 : Connection request timed out

python - Numpy 向量化零阶插值

python - Python 3.4 Docker 容器中的 AWS Elastic Beanstalk 容器命令

c# - 基于两个属性从列表中选择不同值的最快方法