mbm
mbm

Reputation: 1922

Socket Connection: Python

So I'm trying to send several iterations of a barcode file to a device. This is the relevant part of the code:

# Start is the first barcode
start = 1234567

# Number is the quantity
number = 3

with open('barcode2.xml', 'rt') as f:
    tree = ElementTree.parse(f)

# Iterate over all elements in a tree for the root element
for node in tree.getiterator():

    # Looks for the node tag called 'variable', which is the name assigned
    # to the accession number value
    if node.tag == "variable":

        # Iterates over a list whose range is specified by the command
        # line argument 'number'
        for barcode in range(number):

            # The 'A-' prefix and the 'start' argument from the command
            # line are assigned to variable 'accession'
            accession = "A-" + str(start)

            # Start counter is incremented by 1
            start += 1

            # The node ('variable') text is the accession number.
            # The acccession variable is assigned to node text.
            node.text = accession

            # Writes out to an XML file
            tree.write("barcode2.xml")

            header = "<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE labels SYSTEM \"label.dtd\">\n"

            with open("barcode2.xml", "r+") as f:
                old = f.read()
                f.seek(0)
                f.write(header + old)

            # Create socket
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            # Connect to server
            host = "xxx.xx.xx.x"
            port = 9100             
            sock.connect((host, port))

            # Open XML file and read its contents
            target_file = open("barcode2.xml")   
            barc_file_text = target_file.read()         

            # Send to printer
            sock.sendall(barc_file_text)  

            # Close connection
            sock.close()

This is very much a version one.

The device is failing to receive the files after the first one. Could this be because the port is being reused again too quickly? What's a better way to architect this? Thanks so much for your help.

Upvotes: 0

Views: 1378

Answers (1)

Karl Knechtel
Karl Knechtel

Reputation: 61616

target_file = open("barcode2.xml")   
barc_file_text = target_file.read()         
sock.sendall(barc_file_text)  
sock.close()

The socket gets closed, but the file doesn't. The next time through the loop, there is already a lock on the file when you get to the with open... part.

Solution: Use with open... here as well. Also, you don't need to baby-step everything; don't give something a name (by assigning it to a variable) if it isn't important.

with open("barcode2.xml", "r") as to_send:
    sock.sendall(to_send.read())
sock.close()

Upvotes: 4

Related Questions