套接字连接:Python

2024-09-27 01:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着把一个条形码文件的多次迭代发送到一个设备上。这是准则的相关部分:

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

这完全是一个版本。在

设备无法接收第一个文件之后的文件。这可能是因为端口再次被重用的速度太快了吗?有什么更好的设计方法?非常感谢你的帮助。在


Tags: thetotextnodetreenumberforis
1条回答
网友
1楼 · 发布于 2024-09-27 01:26:32
target_file = open("barcode2.xml")   
barc_file_text = target_file.read()         
sock.sendall(barc_file_text)  
sock.close()

套接字被关闭,但文件没有关闭。下一次通过循环时,当您到达with open...部分时,文件上已经有一个锁。在

解决方案:在这里也使用with open...。另外,你不需要一步一步地去做每件事;不要给一个不重要的东西起一个名字(通过给一个变量赋值)。在

^{pr2}$

相关问题 更多 >

    热门问题