套接字连接:Python

0 投票
1 回答
1377 浏览
提问于 2025-04-16 08:09

我正在尝试把几个条形码文件发送到一个设备。这是代码中相关的部分:

# 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()

这只是第一版。

设备在接收到第一个文件后,之后的文件就收不到了。这可能是因为端口被太快地重复使用了吗?有没有更好的方法来设计这个?非常感谢你的帮助。

1 个回答

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

这个问题是说,虽然连接被关闭了,但文件却没有关闭。下次循环的时候,当你到达 with open... 的那部分时,文件已经被锁住了。

解决办法是:在这里也使用 with open...。另外,不需要把每个东西都细致到给它起个名字(也就是赋值给一个变量),如果这个东西不重要的话,就不需要这么做。

撰写回答