Python thread

Asked

Viewed 232 times

0

To be very quick I’m trying to create 10 threads so that 10 attempts at a time are made, that is, from 10 to 10 so that the process is streamlined saving time and processing(maybe), my initial code is as follows:

import threading
import requests
import time

url = 'https://www.nitrxgen.net/md5db/'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:72.0) Gecko/20100101 Firefox/72.0'}

class MyThread(threading.Thread):
    def __init__(self, number):
        super(MyThread, self).__init__()
        self.number = number
    def run(self):
        time.sleep(0.5)
        print('Rodando ' + str(self.number))
        with open('/Users/user/Documents/4500md5hashss.txt', 'r') as f:
            for line in f:
                line = line.replace('\n', '')
                s = line.split(';')
                r = requests.get(url + s[0], headers=headers)
                # print r.url
                if r.content == '':
                    print 'Falha'
                else:
                    print(s[1] + '|' + r.content)


thread_list = []
for i in range(10):
    thread = MyThread(i)
    thread_list.append(thread)
    thread.start()

for thread in thread_list:
    thread.join()

print('finalizado')

The problem is that in this way it does not work right, apparently it is not creating 10 "instances", how should I proceed? my thread is correct?

1 answer

1

Friend, in this case you are instantiating every time, I recommend that if possible, modify the form of execution of your code, so that you start in the thread outside it, below follows an example of a code that uses multiprocessing. Using the parameters target and args or kwargs

from multiprocessing import Process

class Mprocess:

  @staticmethod
  def excel():  
      try:
            pt = [1,2,3,4]    
            proc = []
            for k in range(len(pt)):
                proc.append(Process(target=clx.convert1, args=(pt[k], from_path, to_path,)))
            for p in proc:
                p.start()
            for p in proc:
                p.join()    
             return 
      except Exception as e:
          'some exception'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.