need for script to loop through an array or values

For starters, I am not a Python programmer.  I have devoted the last 3 years working with VB.NET so I am coming to you wonderful experts that have helped me dramatically with this one.  

The script is in place but the goal for this script is to loop through an array or values and build a message based on those values.  We had a need for this script to loop through multiple arrays (varValuesList1 & varValuesList2).  This script does just that and allows us to pause x seconds between each loop.  The idea was that as a message is generated it would send out to the defined port.  What actually happens is the messages are sent in a burst once the script completes running.  We need the script modified so it will send messages out real-time as they are created to the port specified.

The command used to execute this script looks like this c:\Python25> 7000 samplegenericdevice3  Obviously the port number can be whatever we want.

"""Server for the Sample Generic Device DDI
from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols import policies
from string import lower
import time, random, sys
class variableSender(Protocol, policies.TimeoutMixin):
    """The Protocol variableSender sends numToSend random variables chosen in varList with random values every timeout seconds.
        The packet sent does not have a fixed length but is composed of a header, numToSend variable/value blocks and end marker.
        Its general format is "$LLLL#AAAA:BBBB.CCCCCCCCC,;" where "AAAA:BBBB.CCCCCCCCC," is sent "LLLL" times.
        The format of the header is "$LLLL#" where:
            - "$": Is the beginning marker at offset 0
            - "LLLL": Is the number of variable/value blocks in the group at offset 1 as an unsigned integer in a 4-character long string padded with 0
            - "#": Is the header end marker at offset 5
        The format of the fixed-length 20-byte packet sent is "AAAA:BBBB.CCCCCCCCC," where:
            - "AAAA": Is the variable number at offset 0 sent as an unsigned integer in a 4-character long string padded with 0
            - ":": Is the separator between the variable number and its value at offset 4
            - "BBBB.CCCCCCCCC": Is the value at offset 5 sent as a floating point number with a fixed-sized 4-character signed integer part padded with 0 and a fixed-sized 9-character decimal part padded with 0
            - ",": Is the end market at offset 19
        The packet end marker is ";".
        The values are all between -999.999999999 and 9999.999999999.
    timeout = 1
    varList = range(1, 251)
    numToSend = 50
    def __init__(self):
        print "1"
        self.timeout = timeout
    def connectionMade(self):
        print "2"
        print "Got new client!"
        self.timeSent = time.clock()
    def connectionLost(self, reason):
        print "3"
        print "Lost a client:", reason.getErrorMessage()
    def sendHeader(self):
        print "4"
        self.transport.write("$%04d#" % self.numToSend)
    def sendBlockDelimiter(self):
#        print "5"
    def sendEndMarker(self):
        print "6"
    def sendVariable(self, variable, value):
#        print "7"
        self.transport.write("%04d:%014.9f" % (variable, value))
    def sendVariables(self):
        """Send a random selection of numToSend variables from varList with random values.
        print "8"
        varListToSend = random.sample(self.varList, self.numToSend)
        for i in varListToSend:
            self.sendVariable(i, random.random()*10999-999)
    def timeoutConnection(self):
        """Send variables once the timeout is reached.
        print "9a"
#        print "timeout is", self.timeout
        print "9b"
        currentTime = time.clock()
        print "9c"
        print "9d"
        print "Sending Variables", repr(currentTime - self.timeSent)
        print "9e"
        self.timeSent = currentTime
class samplegenericdevice(variableSender):
    """Sample Generic Device, sends a random selection of 200 variables among 250 every 5 seconds.
    def __init__(self):
        self.timeout = 1
        self.varList = range(1, 251)
        self.numToSend = 200
class samplegenericdevice2(variableSender):
    """Sample Generic Device 2, sends 100 variables every 10 seconds.
    def __init__(self):
        self.timeout = 1
        self.varList = range(1, 101)
        self.numToSend = 100
class samplegenericdevice3(variableSender):
    """Sample Generic Device 3, sends 10 variables with predefined values every 3 seconds.
    def __init__(self):
        print "10"
        self.timeout = 1
        self.varValuesList1 = [90, 85, 84, 89, 12, 67, 93, 23, 56, 92]
        self.varValuesList2 = [10, 25, 34, 49, 52, 17, 73, 83, 96, 12]
    def wait(self, seconds):
        """wait(5) => 5 
        print "11"
        Wait for a certain number of seconds before returning.
        Returns the same number passed in."""
#        print time.asctime(), "Waiting %s seconds" % seconds
#        print time.asctime(), "Finished waiting %s seconds" % seconds
        return seconds
    def sendVariables(self):
        """Send all variables from varValuesList.
	print "12"
	for a in range(10):
		for i in range(0, len(self.varValuesList1)):
#		    print "in i loop", i
		    self.sendVariable(i+1, self.varValuesList1[i])
	for b in range(10):
		for z in range(0, len(self.varValuesList2)):
#		    print "in z loop", z
		    self.sendVariable(z+1, self.varValuesList2[z])
def main():
    print "13"
    if len(sys.argv) < 3:
        print sys.argv[0]+": You must provide a port and DDI"
    f = Factory()
    f.protocol = globals()[lower(sys.argv[2])]
    reactor.listenTCP(int(sys.argv[1]), f)
if __name__ == '__main__':
    print "14"

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

HonorGodSoftware EngineerCommented:
It sounds like you are getting hit by buffering.  Python might be trying to "help" you by holding data until the output buffer is full.  Unfortuately, you don't want buffering.

Look at the documentation for:

open( filename[, mode[, bufsize]])

when bufsize = 0 => "0 means unbuffered"
HonorGodSoftware EngineerCommented:
Or, you could simply use flush() after every output...

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
chrisryhalAuthor Commented:
I appreciate everything.  The flush helped out.  Thanks again!!
HonorGodSoftware EngineerCommented:
Great, glad to hear it.
Good luck
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.