测试条件不工作
Test condition not work
我正在使用 python 和 select 以及系统库代码:
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' 字符的不同内容,程序也会停止,但问题是条件不起作用,我进行了测试以查看sys.stdin
值的结果他给了我 'f 字符但是当我把结果放在 if 语句中时程序不工作
结果的截图:
enter image description here
有人能告诉我这个结果的原因吗?
我对 select
图书馆了解不多。但是这里有一个错误立即引起了我的注意。
您使用 k=sys.stdin.readline()
从输入中读取。这意味着 k
将包含完整的行,包括 \n
(换行符)符号。因此,如果您按 f + Enter
,k
的值将是 "f\n"
,而不是 "f"
。这就是为什么比较总是错误的原因。
最好将值与 if k.strip() == "f":
进行比较。
编辑
刚刚快速浏览了 select
库。如果要确定是否发生超时,则需要使用 select 函数的 return 值。而不是直接从输入中读取。否则,无论是否发生超时,您都将等待。
我不确定你想要完成什么,但类似于以下代码的东西会起作用。
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 和 select 以及系统库代码:
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' 字符的不同内容,程序也会停止,但问题是条件不起作用,我进行了测试以查看sys.stdin
值的结果他给了我 'f 字符但是当我把结果放在 if 语句中时程序不工作
结果的截图:
enter image description here
有人能告诉我这个结果的原因吗?
我对 select
图书馆了解不多。但是这里有一个错误立即引起了我的注意。
您使用 k=sys.stdin.readline()
从输入中读取。这意味着 k
将包含完整的行,包括 \n
(换行符)符号。因此,如果您按 f + Enter
,k
的值将是 "f\n"
,而不是 "f"
。这就是为什么比较总是错误的原因。
最好将值与 if k.strip() == "f":
进行比较。
编辑
刚刚快速浏览了 select
库。如果要确定是否发生超时,则需要使用 select 函数的 return 值。而不是直接从输入中读取。否则,无论是否发生超时,您都将等待。
我不确定你想要完成什么,但类似于以下代码的东西会起作用。
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))