2017-09-23 60 views
0

因此,我现在玩的线程和我已经到了舞台,线程确实工作,但我认为我有问题for循环。所以for循环只能在代码内部工作,但每当我想让它遍历整个代码时。然后,它将只取得Json文件中的最后一个对象。Python - For循环和线程不想一起工作?

代码

#Read json File 
with open('config.json', 'r', encoding='UTF-8') as json_data: 
    config = json.load(json_data) 

threads = [] 
for i in range(len(config)): 
    p = threading.Thread(args=(config[i])) 
    threads.append(p) 
    p.start() 
    print() 
    print(config[i]) 


NameUrl = config[i]["Url"] 

myNote = config[i]["My-Note"] 

def checkoutNames(NameUrl, nameID): 

#Request & other codes - Removed to recude the code 
#...... 
#...... 
    headers = { 
     'Referer': '', 
     'Content-Type': '' 
    } 
    payload = { 
     "shared": { 
      "challenge": { 
       "email": config[i]["Email"], 
       "PersonNumber": config[i]["PersonNumber"], 
       "postal_code": config[i]["ZipCode"], 
       "given_name": config[i]["Name"], 
       "Last_name": config[i]["LastName"], 
       "street_address": config[i]["Address"], 
       "postal_code": config[i]["ZipCode"], 
       "city": config[i]["City"], 
       "country": config[i]["Country"], 
       "email": config[i]["Email"], 
       "phone": config[i]["Phone"], 
      } 

def checkoutNotes(NamesUrl, NamesPost): 

#Request & other codes - Removed to recude the code 
#...... 
#...... 

    headers = { 
     'Accept': 'application/json, text/javascript, /; q=0.01', 
     'Accept-Language': 'en-US,en;q=0.5', 
     'Accept-Encoding': 'gzip, deflate, br', 
     'Referer': NameUrl, 
     'Connection': 'keep-alive' 
    } 
    payloadInfo = { 
     "Information": { 
      "Color": config[i]["Color"], 
      "house_number": config[i]["houseNumber"], 
      "year": config[i]["Year"] 
     } 
    }  
def wipe(): 
    os.system('cls' if os.name == 'nt' else 'clear') 

def main(): 
    time.sleep(1) 

    FindName(myNote) 

if _name_ == '_main_': 
    try: { 
     main() 
    } 
    except KeyboardInterrupt: 
     wipe() 

所以你可以看到代码中有一个线程在开始,但我不知道为什么的问题它不经过整个代码?也许任何看到这个问题?

这是问题

threads = [] 
for i in range(len(config)): 
    p = threading.Thread(args=(config[i])) 
    threads.append(p) 
    p.start() 
    print() 
    print(config[i]) 
+0

而且请。如果有什么缺失。随时发表评论,我会马上发布! – WeInThis

回答

1

你应该给一个目标线程,如果不存在使用多线程是没有意义的。

#p = threading.Thread(target=function_name, args=(config[i])) 
#try something like this 
def yourfucntion(config): 
    #do your thing 
    pass 
if __name__ =='__main__': 
    with open('config.json', 'r', encoding='UTF-8') as json_data: 
      config = json.load(json_data) 
    threads=[] 
    for i,e in enum(config): 
      threads.append(threading.Thread(target=yourfunction,args=(config[i] or e)) 
+0

哦。如果我想要开始跑步,如果我可能会问,我的目标是什么?就像从顶端?就像我在展示的代码中一样? – WeInThis

+0

为什么你在代码中使用线程?你想实现什么? – Perseus784

+0

哦。基本上我已经例证了5-20个json对象。我希望他们如何让他们通过每个线程来完成整体进度。这样每个json对象都将通过代码运行自己的Json信息。很多,你了解概念? – WeInThis