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

これは非常にバージョン1です。

デバイスは、最初のファイルの受信後にファイルの受信に失敗しています。これは、ポートが再びあまりにも早く再利用されているためでしょうか?これをよりうまく構築する方法は何ですか?助けてくれてありがとう。

+0

「ElementTree」は自分のクラスですか? 'getiterator'の名前が' __iter__'に変更された場合、 'tree for:'の 'for node:'を使うことができます。これはもっとPythonicです。また、ヘッダーを書くことができないのはなぜですか? –

+0

いいえ、ElementTreeはxml.etreeから来ます。それはヘッダーを書きます、私はちょうどソケット接続を働かせることができません。 – mbm

答えて

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() 
+0

ヘルプカールありがとう! – mbm