0

У меня есть программа которая работает перебором и сравнением с помощью цикла. Я сделал ей интерфейс и когда в интерфейса нажимаю запустить - она зависает при любом клике. Как сделать несколько потоков в такой программе?

Интерфейс на pysimpleGui

import string
import PySimpleGUI as sg
from numba import njit, prange
import time

string.digits + string.ascii_letters + string.punctuation + string.digits
alph = string.ascii_uppercase


def decrypt(message, key):
    return algo(message, key, -1)


def algo(text, k, op):
    k *= len(text) // len(k) + 1
    return ''.join(alph[alph.index(j) + int(k[i]) * op] for i, j in enumerate(text))


def encrypt(message, key):
    return algo(message, key, 1)


f = open('words.txt')
dictionary = f.readlines()

duplicate_wordss = []
dictionary = set(word.strip().lower() for word in dictionary)


def brute(word_decode):
    for x in prange(10000000):
        s = decrypt(word_decode.upper(), str(x))
        if s.lower() in dictionary:

            for i in duplicate_wordss:
                if i == s.lower(): break
            else:
                duplicate_wordss.append(s.lower())
                print(s + ' Key - ' + str(x))


def start(word):
    cur_time = time.time()
    brute(word)
    end_time = time.time()
    total_time = end_time - cur_time
    print('Time: ' + str(total_time))
    f.close()


def main():
    layout = [[sg.Text('Enter your text')],
              [sg.Input(key='_IN_')],  # input field where you'll type command
              [sg.Output(size=(60, 15))],  # an output area where all print output will go
              [sg.Button('Decrypt'), sg.Button('Exit')]]  # a couple of buttons

    window = sg.Window('Gronsfeld cipher - auto decryptor', layout)
    while True:  # Event Loop
        event, values = window.Read()
        if event in (None, 'Exit'):  # checks if user wants to
            exit
            break

        if event == 'Decrypt':  # the two lines of code needed to get button and run command
            # runCommand(cmd=values['_IN_'], window=window)
            word_decode = values['_IN_']
            start(word_decode)

    window.Close()


if __name__ == '__main__':
    main()
7
  • пожалуйста, предоставьте минимальный воспроизводимый пример, который демонстрирует проблему.
    – S. Nick
    22 мар 2022 в 16:50
  • Обновил вопрос, добавил код
    – xmmsq31
    22 мар 2022 в 17:30
  • В консоли pycharm всё нормально работает то есть проблема не в коде, просто нужно как то создать отдельный поток для интерфейса
    – xmmsq31
    22 мар 2022 в 17:32
  • Добавьте, пожалуйста, импортируемые библиотеки, что бы можно было протестировать ваш код.
    – arnold
    22 мар 2022 в 17:37
  • Да конечно, обновил код
    – xmmsq31
    22 мар 2022 в 17:39

1 ответ 1

0

Пришлось немного напрячься, так как не был знаком с модулем PySimpleGUI, но получилось:

import string
import PySimpleGUI as sg
from numba import njit, prange
import time
import threading

string.digits + string.ascii_letters + string.punctuation + string.digits
alph = string.ascii_uppercase


def decrypt(message, key):
    return algo(message, key, -1)


def algo(text, k, op):
    k *= len(text) // len(k) + 1
    return ''.join(alph[alph.index(j) + int(k[i]) * op] for i, j in enumerate(text))


def encrypt(message, key):
    return algo(message, key, 1)


f = open('words.txt')
dictionary = f.readlines()

duplicate_wordss = []
dictionary = set(word.strip().lower() for word in dictionary)


def brute(word_decode):
    for x in prange(10000000):
        s = decrypt(word_decode.upper(), str(x))
        if s.lower() in dictionary:

            for i in duplicate_wordss:
                if i == s.lower(): break
            else:
                duplicate_wordss.append(s.lower())
                print(s + ' Key - ' + str(x))


def start(word):
    cur_time = time.time()
    t = threading.Thread(target=brute, args=(word,))
    t.start()


    end_time = time.time()
    total_time = end_time - cur_time
    print('Time: ' + str(total_time))
    f.close()


def main():
    layout = [[sg.Text('Enter your text')],
              [sg.Input(key='_IN_')],  # input field where you'll type command
              [sg.Output(size=(60, 15))],  # an output area where all print output will go
              [sg.Button('Decrypt'), sg.Button('Exit')]]  # a couple of buttons

    window = sg.Window('Gronsfeld cipher - auto decryptor', layout)
    while True:  # Event Loop
        event, values = window.Read()
        if event in (None, 'Exit'):  # checks if user wants to
            exit
            break

        if event == 'Decrypt':  # the two lines of code needed to get button and run command
            # runCommand(cmd=values['_IN_'], window=window)
            word_decode = values['_IN_']
            t = threading.Thread(target=start, args=(word_decode,))
            t.start()
            # start(word_decode)

    window.Close()


if __name__ == '__main__':
    main()
2
  • Спасибо большое, работает, не могли бы вы подсказать как еще можно ускорить выполнение данного кода ?)
    – xmmsq31
    22 мар 2022 в 19:22
  • Честно сказать, нету времени вникать в ваш код, уж извините) С виду всё вполне неплохо выглядит.
    – arnold
    22 мар 2022 в 19:48

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.