Python - мультипроцессинг, дать каждому процессору электронное письмо из текстового файла - PullRequest
0 голосов
/ 30 мая 2018

Итак, я поигрался с Multiprocessing, и я думал об улучшении моих знаний, чтобы я мог прочитать первое предложение из текстового файла для процесса 1, затем второе предложение для процесса 2 и т. Д. *

txt file:

helloworld@world.com
helloworld2@world.com
helloworld3@world.com
helloworld4@world.com
helloworld5@world.com

и вот как выглядит код:

def info(thread):
    global prod
    prod = int(thread) + 1
    runit()


def runit():

    log("Profile-" + str(prod) + Fore.GREEN + ' - ' + email)
    #From here I can then use the email for each worker basically. Or thats the plan atleast. Theplan is that every worker will have its own email that can be used in here.
    sys.exit()

def main():
    user_input = 0
    while True:
        try:
            user_input = int(input(Fore.WHITE + 'How many tasks do you wanna run? [NUMBERS] \n' + Fore.RESET))
        except ValueError:
            print(Fore.RED + "Stop being stupid" + Fore.RESET)
            continue
        else:
            with open('email.txt') as f:
                content = f.readlines()
            content = [x.strip('\n') for x in content]

            try:
                for i, email in enumerate(content):
                    print(email)

            except ValueError as e:
                print(e)

            HowManyThread = user_input
            i = 0
            jobs = []
            for i in range(HowManyThread):
                p = multiprocessing.Process(target=info, args=(str(i),))
                jobs.append(p)
                time.sleep(.5)
                p.start()

            for p in jobs:
                p.join()

            sys.exit()

Журнал - это просто сообщение журнала, ничего особенного

Fore.COLOR <- Colorama </h2> Однако я совершенно не представляю, что мне следует делать, чтобы каждый процесс занимал каждую строку электронной почты.Так что в основном .... Process-1 to take helloworld@world.com Process-2 to take helloworld2@world.com Process-3 to take helloworld3@world.com Process-4 to take helloworld4@world.com Process-5 to take helloworld5@world.com Какие предложения о том, как я могу это сделать?Я полностью отключен и не знаю, как двигаться дальше. Обновление from multiprocessing import pool, Process, Queue from tqdm import tqdm with open('email.txt') as f: content = f.readlines() global email_list email_list = [x.strip('\n') for x in content] def info(thread): global prod prod = int(thread) + 1 runit() def runit(email_index): email = email_list[email_index] log("Profile-" + str(prod) + Fore.GREEN + ' - ' + email) sys.exit() def main(): wipe() text() Infotext = "First name : Last name : Email: : Random char + Street" with open('data.json', 'w') as f: json.dump(Infotext, f) f.write("\n") with Pool(8) as pool: result_list = list(tqdm(pool.imap_unordered(, range(len(email_list)), chunksize=5), total=len(email_list)))) if __name__ == '__main__': try: main() except Exception as e: print(e) print(traceback.print_exc()) print(traceback)

Ответы [ 2 ]

0 голосов
/ 30 мая 2018

Вам нужен пул рабочих процессов - даже если вам нужен сценарий, мне действительно интересно, не хватит ли потоков (или multiprocessing.dummy).

Пул запускает запрошенное количество рабочихпроцессов, и вы можете отправлять асинхронные задачи в пул, который будет обрабатываться первой бесплатной обработкой.

Урезанная версия вашего примера (не нужно печатать, не нужно читать последовательный файл в списке)может быть:

import multiprocessing
import time

def runit(prod, email):

    print("Profile-" + str(prod) + ' - ' + email)
    #From here I can then use the email for each worker basically. Or thats the plan atleast. Theplan is that every worker will have its own email that can be used in here.
    # sys.exit() # NEVER CALL EXPLICITELY sys.exit() in a worker process
    time.sleep(1) # to add a delay inside each task

def main():
    while True:
        try:
            HowManyThread = int(input(
                'How many tasks do you wanna run? [NUMBERS] \n'))
        except ValueError:
            print("Stop being stupid")
            continue

        if HowManyThread == 0: break

        pool = multiprocessing.Pool(HowManyThread)
        with open('email.txt') as f:
            for i, email in enumerate(f):
                email = email.strip()
                # runit will be runned by a worker process
                pool.apply_async(runit, (i, email))

        pool.close()         # no more task to add
        pool.join()          # wait for last worker to end

if __name__ == "__main__":
    main()
0 голосов
/ 30 мая 2018

Следующий подход делегирует многопроцессорную обработку пулу рабочих, каждый из которых получает набор индексов и обрабатывает эти индексы по одной строке за раз (выбор poolsize=8 и chunksize=5 здесь произвольный и может бытьнастроены в соответствии с вашими требованиями).

Результаты всех работников затем собираются в окончательный список.Обратите внимание, что imap_unordered подходит только в том случае, если вас не волнует порядок, в котором обрабатываются строки (т. Е. result_list не поддерживает исходный порядок content.

from multiprocessing import Pool
# progress bar to track your multiproc
from tqdm import tqdm

with open('email.txt') as f:
    content = f.readlines()

# this list will be accessed by each worker
global email_list
email_list = [x.strip('\n') for x in content]

# define function that worker will apply to each email
# it gets sent an index for the list of emails
# it accesses the email at that index, performs its function and returns
def runit(email_index):
    email = email_list[email_index]
    # do the stuff you're interested in for a single email

# run the multiprocessing to get your results
# this sends the indexes for the emails out to the workers
# and collects the results of runit into result list
with Pool(8) as pool:                                                
  result_list = list(tqdm(pool.imap_unordered(runit,    
                          range(len(email_list)), chunksize=5),                 
                          total=len(email_list)))
.
...