0

I'm new in python. I've found a simple TCP Server's code and it works. The problem is: i'm not able to make a if...elif...else works. I think it's a mistake of value's type.

Here's my code (the program always do the else part):

while 1:
    data = clientsocket.recv(1024)
    tokens = data.split(' ',1)
    command = tokens[0]
    if not command:
        break
    else:
        if command == 1:
            try:
                camera.start_preview()
                time.sleep(10)
                camera.stop_preview()
            finally:
                camera.close()
        elif command == 2:
            print "Something"
        elif command == 3:
            print "something else"
        else:
            print data
            print tokens[0]
            print command
clientsocket.close()

It give me the result of the last else which is :

2

2

2

Or the number I send. Thanks in advance for your responses !

3
  • try command = int(tokens[0]) since the data received is a string and not int Commented Jun 25, 2014 at 15:06
  • @SebastienVoisard print out the value of data and finally of command, it will give you the answer. Even better, try to debug the code (using pdb or ipdb), and inspect the changes step by step). See pymotw.com/2/pdb Commented Jun 25, 2014 at 15:10
  • You were right, the type was not the same, thanks, it works now ! Commented Jun 25, 2014 at 15:47

1 Answer 1

3

command is a string, not an integer; you are comparing:

>>> '2' == 2
False

Instead, use:

...
tokens = data.split(' ', 1)
try:
    command = int(tokens[0])
except ValueError:
    break

if command == 1:
    ...
Sign up to request clarification or add additional context in comments.

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.