mksmvnv
@mksmvnv

Почему вылетает программа в ходе работы через консоль Python?

Сразу прошу не судить, недавно начал заниматься Python и могу задать глупый вопрос.
В общем, я загорелся написать простой шифратор текстовых файлов. В коде нет ничего сверхъестественного. Просто для отработки базовых навыков и парочки библиотек, решил испытать себя. В итоге программа получилась и через IDE Pycharm и VS Code работает корректно. Однако, если я хочу запустить программу через консоль Python, то после сохранения пароля пользователя в текстовый файл "База данных паролей" (12 строка кода), консоль резко вылетает и больше никаких действий не происходит. Так как в IDE все работает корректно, я не могу выловить в чем же ошибка. Буду рад, если вы мне подскажите, что нужно исправить. Спасибо!

import pyAesCrypt
import sys, traceback
from pathlib import Path, PurePath

incorrect_value = 0  # variable to indicate incorrect password value
task_type = input('Do you want to encrypt or decrypt your file? [Encrypt/Decrypt]: ').title()  # selecting a task type

if task_type == 'Encrypt':
    def get_encrypt():
        password = input('Please enter the password to encrypt this file: ')  # creating a user password
        password_database = open('password_database.txt', 'w')  # creating a password database
        password_database.write(password)  # writing the password to the password database
        if len(password) == incorrect_value:
            print('Error. Your password is empty, please try again.')
            sys.exit()
        user_path = input('Please enter the path to your file (along with the file name): ')  # user entering
        # the absolute path to the encryption file
        if Path(user_path).is_file():  # checking if this path is the directory with the file
            list_user_path = PurePath(user_path).parts  # splitting the path with slashes into list objects
            file_name = list_user_path[-1]  # selecting the main file name from the end of the list
            # encryption process
            pyAesCrypt.encryptFile(f'{file_name}', f'encrypted_{file_name}.aes', password)
        else:
            print('You did not specify the absolute path to the file, please try again.')
            sys.exit()


    get_encrypt()

elif task_type == 'Decrypt':
    def get_decrypt():
        password_check = input('Please enter the password to decrypt this file: ')  # entering verification password
        encrypted_password_file = open('password_database.txt', 'r')  # viewing the password database
        encryption_password = encrypted_password_file.read()  # uploading a password from the database for comparison
        if password_check != encryption_password:  # password comparison
            print('Error. You entered an incorrect decryption password, please try again.')
            sys.exit()
        user_path = input('Please enter the path to your file (along with the file name): ')  # user entering
        # the absolute path to the encryption file
        if Path(user_path).is_file():  # checking if this path is the directory with the file
            list_user_path = PurePath(user_path).parts  # splitting the path with slashes into list objects
            file_name = list_user_path[-1]  # selecting the main file name from the end of the list
            file_name_without_encryption_format = PurePath(user_path).stem  # removing the encryption format
            # from the end of the file
            original_file_name = file_name_without_encryption_format[10:]  # removing part of the file name
            # for correct output
            # decryption process
            pyAesCrypt.decryptFile(f'{file_name}', f'decrypted_{original_file_name}', password_check)
        else:
            print('You did not specify the absolute path to the file, please try again.')
            sys.exit()


    get_decrypt()

else:
    print('Error.You entered incorrect data to continue the correct operation of the program, try again.')
    sys.exit()
  • Вопрос задан
  • 172 просмотра
Решения вопроса 1
AshBlade
@AshBlade
Просто хочу быть счастливым
Скорее всего проблема в этой строке:
encrypted_password_file = open('password_database.txt', 'r')  # viewing the password database


Ты указываешь локальный путь к файлу - относительно рабочей директории. При запуске она может быть не той, где лежит файл password_database

P.S. открывать файлы лучше через
with open('password_database.txt', 'rt') as encrypted_password_file:
     # код

поищи что такое контекстные менеджеры
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы