2010-12-06 204 views
0

所以我试图发送一个条码文件到设备的几次迭代。这是代码的相关部分:套接字连接: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() 

这是非常一个版本。

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

+0

ElementTree是你自己的班级吗?如果`getiterator`被重命名为`__iter__`,那么你可以使用'for tree:`这个更加Pythonic的节点。另外,为什么你不能为它写头文件? – 2010-12-06 23:43:00

+0

不,ElementTree来自xml.etree。它会写头,我只是不能让套接字连接工作。 – mbm 2010-12-06 23:48:29

回答

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

套接字被关闭,但文件没有关闭。下一次循环时,当你到达with open...部分时,文件已经锁定。

解决方案:此处也使用with open...。另外,你不需要对所有的东西进行小步步操;如果它不重要,不要给某个名称(通过将它分配给一个变量)。

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