2017-08-29 150 views
1

下面的類正在讓我瘋狂。它卡在for循環中。我不確定爲什麼它不會訪問self.job_ids中的最後一個元素。這應該是工作。任何想法爲什麼這個for循環在類內部不起作用,但它在課堂以外完美地發現了嗎?for循環不訪問列表中的所有元素python

進口子

class job_runner(): 

    def __init__(self, user_id='staffner'): 
     self.job_ids = ['12054807', '12054808', '12054809', '12054810', '12054811', '12054812', '12054813', '10', '100'] 

     self.user_id = user_id 

    def update_running_jobs(self): 
     ''' 
      () -> 
      Remove job ids from self.job_ids which completed 
     ''' 
     # find currently running jobs 
     curr_running = self.find_running_jobs() 

     #iterate over self.job_ids and see if they are in the currently running jobs 
     working_ids = self.job_ids 
     print 'start working ids:' 
     print working_ids 
     for j_id in working_ids: 

      # for some reason I can not access the last id in the list 
      print j_id 

      if j_id not in curr_running: 
       self.job_ids.remove(j_id) 
     print 'job_ids' 
     print self.job_ids 

    def find_running_jobs(self): 
     ''' 
      () -> list running ids 

      Find what job ids are still running on the high performance cluster 
     ''' 
     proc = subprocess.Popen(['squeue -u %s --Format=arrayjobid'%(self.user_id)], stdout=subprocess.PIPE, shell=True) 
     out, err = proc.communicate() 

     if err == None: 

      out_list = out.replace('ARRAY_JOB_ID', '').replace(' ', '').split('\n') 

      # filter out any empty strings 
      out_list = filter(None, out_list) 
      return out_list 

     else: 
      return False 

curr_jobs = job_runner() 

curr_jobs.update_running_jobs() 

這裏的輸出(因爲你可以看到100從不訪問):

start working ids: 
['12054807', '12054808', '12054809', '12054810', '12054811', '12054812', '12054813', '10', '100'] 
12054807 
12054808 
12054809 
12054810 
12054811 
12054812 
12054813 
10 
job_ids 
['12054807', '12054808', '12054809', '12054810', '12054811', '12054812', '12054813', '100'] 
+0

它可以在我的機器上正常工作 – alfasin

+0

有沒有任何理由不能在一臺機器上工作,但在另一臺機器上工作? – Samantha

+1

如果我刪除了'find_running_jobs()'調用,並且它與代碼中的相關循環顯示了所有項目,但是運行完整代碼,我的機器打印了'100',但不打印'10'! – Juggernaut

回答

4

你應該改變:

working_ids = self.job_ids 

到:

working_ids = self.job_ids[:] # create a copy of job_ids and use it 

說明:您在修改列表的同時迭代它會導致意外的結果,更改代碼將迭代列表的副本

+0

非常感謝。我以爲我在製作一個副本。 – Samantha

+0

@Samantha只記得*賦值永遠不會在Python中複製*。 –

+0

「...永遠不會複製_data_」 - 它複製對象的引用 – holdenweb

相關問題