0

Sorry if this is a common question, but every solution I've looked up so far doesn't seem to work.

Basically, I want this loop to exit when the user enters "end" but for some reason it won't actually break the loop.

command = input("Enter command: ") + "\r\n"
while(True):
    print(command)
    if command == "end":
        break
    else:
        tn.write(command.encode("utf-8"))
        ret1 = tn.read_until(b"_DNE", timeout = 10)
        print(ret1)
        command = input("Enter command: ") + "\r\n"

If the user inputs "end" it seems like it ignores the "if" statement and just skips straight to "else"

3
  • Have you tried command == "end\r\n" or command == "end\n\r\n"? Commented Aug 17, 2015 at 15:45
  • Why are you appending \r\n to the end of your input string? Commented Aug 17, 2015 at 15:56
  • @ILostMySpoon looks like he's writing to a device that probably uses \r\n as a terminator. That said, I think the best option is probably to define a communicate function that looks like gist.github.com/NotTheEconomist/aa7672106d93bc4079f1 Commented Aug 17, 2015 at 16:04

2 Answers 2

2

Instead of trying to attach \r\n to the end of the user input, use raw_input instead

command = raw_input("Enter command: ")
while(True):
    print(command)
    if command.rstrip('\r\n') == "end":
        break
    else:
        tn.write(command.encode("utf-8"))
        ret1 = tn.read_until(b"_DNE", timeout = 10)
        print(ret1)
        command = raw_input("Enter command: ")
Sign up to request clarification or add additional context in comments.

3 Comments

If the OP is using python 3 (which I think it is), raw_input() got renamed to input()
@Harpal. Ahh I see. makes sense
It worked once I changed your raw_input() back to input(), thanks!
0

Because you add \r\n to your input, whenever you input end, the variable command is holding end\r\n as the string value, not end. So the if statement does not detect it when the user inputs end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.