Reputation: 381
I'm very new to Python... liking it but having a weird problem. Here's some code:
def run(self):
print("receiver starting")
while self.receiving:
print("RX loop")
try:
print("RX: waiting for PDU from peer")
data, addr = self.rx_socket.recvfrom(32)
print("RX: received %d bytes"%(len(data)))
print("RX: self.receiving=%d"%(self.receiving))
print("XXXX RX: 0x%s"%(data.hex()))
# condition seems to be true but block not entered
if self.receiving == 1 & len(data) > 0:
my_pdu = 0
print("ZZZZ RX: 0x%s"%(data.hex()))
As you can see, I have a loop running in a thread which reads from a socket. Now look at this test output:
RX loop
RX: waiting for PDU from peer
RX: received 3 bytes
RX: self.receiving=1
XXXX RX: 0x022000
ZZZZ RX: 0x022000
RX loop
RX: waiting for PDU from peer
RX: received 8 bytes
RX: self.receiving=1
XXXX RX: 0x100100ffff020028
RX loop
RX: waiting for PDU from peer
My first read returns 3 bytes and we see both the XXXX prefixed print statement outside the if block and then the ZZZZ prefixed statement inside the if block, as expected.
The second read returns 8 bytes, prints the XXXX prefixed line but then does not enter the if block despite the condition (self.receiving == 1 & len(data) > 0) both being true according to the printed values prior to the XXXX line.
My thread isn't exiting otherwise I wouldn't see the "RX loop" line again.
Can any of you experienced Python people tell me what I've done wrong here?
Thank you
Upvotes: 0
Views: 129
Reputation: 4010
Since you can write while self.receiving:
, I presume it's a booolean; this means that you can just write if self.receiving
.
&
is the binary/bitwise and
operator and it's probably not what you want here. I think you're after and
.
Try changing
if self.receiving == 1 & len(data) > 0:
to
if self.receiving and len(data) > 0:
Upvotes: 1
Reputation: 20457
The problem is that &
is bitwise and, and you want logical and, which is and
:
if self.receiving == 1 and len(data) > 0:
Upvotes: 3