Sekmani52
Sekmani52

Reputation: 55

Test condition not work

I'm using python with select and system library here the code :

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()

this program wait the user until put a char i put in the program a condition if the user put a char after 5 second so the program stop also if the user give something different of the 'f' char but the problem the condition doesn't work i put a test to see the result of the sys.stdin value he give me the 'f char but when i put the result in the if statement the program don't work this screenshot of the result: enter image description here

Can someone give me the reason of this result ?

Upvotes: 1

Views: 45

Answers (1)

Jakube
Jakube

Reputation: 3575

I don't know much about the select library. But here is an error the immediately caught my eyes.

You read from the input with k=sys.stdin.readline(). This means that k will contain the complete line, including the \n (newline) symbol. So if you press f + Enter the value of k will be "f\n", not "f". This is the reason why the comparison is always wrong.

It would be best to compare the values with if k.strip() == "f":.


Edit

Just had a quick look into the select library. If you want to determine if a timeout happened, you need to work with the return values of the select function. And not read from input directly. Otherwise you will wait regardless if a timeout happened or not.

I'm not sure what you want to accomplish, but something similar to the following code will work.

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))

Upvotes: 2

Related Questions