Could you please give me some advise on this piece of code?

G. bestenborstel at gmail.com
Mon Sep 12 16:51:45 CEST 2011


Dear all,
I am a python newbie, but I intend to program a python script that
communicates with Labview via a UDP socket.
I managed to send LabView strings, but the other way around is not
working.
The code seems to stop working while in the first while loop. I can
see the word "test" being print out.

When I start LabView UDP_sender.vi it is supposed to send a string
back to python, but sometimes it ends with an error saying the port
and the ip is already in usage. Do I have to start first LabView or
the python scrip when listening to LabView, please?

It would be great if you could have a look on my code and could maybe
see why it does nothing after "print test", please.

Thank you very much.

Kind regards,
G.



# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="User"
__date__ ="$11.09.2011 19:34:03$"

if __name__ == "__main__":
    print "Das ist ein Test"

import socket
import time

#Define global variables for UDP_IP and UDP_Port, needs to be changed
for PETRA-3
#global UDP_IP
UDP_IP="127.0.0.1"
print "UDP_IP is", UDP_IP

#global UDP_PORT
UDP_PORT=21312
print "UDP_PORT is", UDP_PORT





def openUDPSocket(UDP_IP,UDP_PORT):
    #UDP_IP="127.0.0.1"
    #UDP_PORT=5005
    print "Creating socket ..."
    sock=socket.socket( socket.AF_INET, # Internet
                        socket.SOCK_DGRAM ) # UDP
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    #sock.setblocking(0)
    #sock.bind((UDP_IP,UDP_PORT))
    #sock.listen(1)
    print "Done."
    return sock

def fastPump(sock):
    # Start pumping and return
    MESSAGE="pumpfast"

   # print "UDP target IP:", UDP_IP
   # print "UDP target port:", UDP_PORT
   # print "message:", MESSAGE

    sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )

def slowPump(sock):
    MESSAGE="pumpslow"
    sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )


pumpsocketUDP=openUDPSocket(UDP_IP,UDP_PORT)


# Receive messages
counter_while_loop=0
print "test"
while counter_while_loop < 3:
	data,addr = pumpsocketUDP.recvfrom(1024)
        print "test"
	if not data:
		print "Client has exited!"
		break
	else:
		print "\nReceived message '", data,"'"
        counter_while_loop=counter_while_loop+1


counter_while_loop=0

while counter_while_loop < 3:
    fastPump(pumpsocketUDP)
    time.sleep(5)
    slowPump(pumpsocketUDP)
    time.sleep(3)

    counter_while_loop=counter_while_loop+1
    print "Counter_while_loop", counter_while_loop


# Close socket
pumpsocketUDP.close()



More information about the Python-list mailing list