2

I'm working with a small script that creates a listening socket and receives a file from a client.

This code works in python 2.7 but I cannot figure out why it doesn't work with python 3. Can someone help me make this work?

import socket
(HOST, PORT) = ('', 19129)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT));
s.listen(1);
conn, addr = s.accept()
with open('LightData.txt', 'wb') as f:
 while True:
 t = conn.recv(20)
 print (t)
 if t == "":
 s.close()
 break
 f.write(t)

It gets stuck somewhere at if t==:, because in the console it keeps printing

b''
b''
b''
b''
b''
b''
b''
baduker
20.2k9 gold badges44 silver badges64 bronze badges
asked Mar 31, 2018 at 10:28
1
  • Try this in an interactive interpreter: b'' == "". Commented Mar 31, 2018 at 10:31

2 Answers 2

2

In python2:

>>> b'' == ''
True

In python3:

>>> b'' == ''
False

So replace if t == "": with if t == b'':

answered Mar 31, 2018 at 10:33
Sign up to request clarification or add additional context in comments.

2 Comments

Something is still not right, after replacing with what you had suggested the console returns, "b'1\n' b'' Process finished with exit code 0 " i am expecting it to return either a 1 or a 0 as the data i'm receiving and put it in the text file LightData.txt
It was working after doing what you had mentioned i had been using a temporary directory in PyCharm...That's why it did not update the file. thanks again for your time!
1

The problem is here:

if t == "":

Your t is binary data, a bytes object. No bytes object is ever equal to a Unicode str object. So this will always fail. Try it yourself:

>>> b'' == ''
False

The reason this worked in Python 2 is that byte-strings and strings were the same type, while unicode strings were a different type. In Python 3, Unicode strings and strings are the same type, while bytes are a different type.


If you'd written this the idiomatic way in Python 2, it would continue to work in Python 3:

if not t:

In Python, you usually just check whether a value is "truthy" or "falsey". A non-empty string and a non-empty byte-string are both truthy; empty ones are both falsey. The only time you want to write a check like if t == "" is when you explicitly want to check only empty strings, and have it fail for None, or False, or empty bytestrings.

answered Mar 31, 2018 at 10:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.