2010-12-06 151 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()