2012-10-05 150 views
1

如何修改此代碼以允許我使用last_coordinates列表與當前的coordinates列表進行比較,以便在這兩個列表之間的值存在差異時可以調用activate()這樣的方法?比較列表值

HOST = '59.191.193.59' 
PORT = 5555 

coordinates = [] 

def connect(): 
    globals()['client_socket'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    client_socket.connect((HOST,PORT)) 

def update_coordinates(): 
    screen_width = 0 
    screen_height = 0 
    while True: 
     try: 
      client_socket.send("loc\n") 
      data = client_socket.recv(8192) 
     except: 
      connect(); 
      continue; 

     globals()['coordinates'] = data.split() 

     if(not(coordinates[-1] == "eom" and coordinates[0] == "start")): 
      continue 

     if (screen_width != int(coordinates[2])): 
     screen_width = int(coordinates[2]) 
       screen_height = int(coordinates[3]) 
     return 

Thread(target=update_coordinates).start() 
connect() 
update_coordinates() 
while True: 
    #compare new and previous coordinates then activate method? 
    activate() 
+0

網絡/套接字代碼與這個問題有什麼關係? – 2012-10-05 08:46:24

+0

你使用'globals()'的任何特定原因? –

+0

在分配給它之前使用'globals coordinates'而不是'globals()['coordinates']',或者使用'coordinates [:] = data.split()'完全避免本地和全局分配問題。 –

回答

0

你需要在模塊範圍內進行初始化last_coordinates

last_coordinates = ['start', 0, 0] 

後來您收到數據後,添加類似下面的代碼:

globals()['coordinates'] = data.split() 
if last_coordinates[0] != coordinates[0] or \ 
    last_coordinates[1] != coordinates[1] or \ 
    last_coordinates[2] != coordinates[2]: 
    # Do something useful here 

# this line copies your coordinates into last_coordinates 
last_coordinates = coordinates[:] 

還有其他問題與您的代碼正如其他人也在評論中指出的那樣。例如。在上面的片段中的第一行可以更好地重寫爲:

global coordinates 
coordinates = data.split() 

但是,那麼你可能仍然有線程問題。