如何在此代码中添加try / except函数?

时间:2016-12-20 14:19:02

标签: python try-except

我仍然在创建这个代码,通过字典攻击,我找到了一个由用户插入的密码。但是我会在文件源的输入中插入一些控件(例如,当我键入不存在的文件的源时),当我打开文件但是里面没有与密码类型相匹配的单词时由用户。我的想法告诉我,我可以使用istructions作为“If,Else,Elif”但其他程序员告诉我除了说明我可以使用try。

这是代码:

"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.

"""


def dictionary_attack(pass_to_be_hacked, source_file):

    try:


        txt_file = open(source_file , "r")

        for line in txt_file:

            new_line = line.strip('\n')


            if new_line == pass_to_be_hacked:

                print "\nThe password that you typed is : " + new_line + "\n"

    except(







print "Please, type a password: "

password_target = raw_input()


print "\nGood, now type the source of the file containing the words used for the attack: "

source_file = raw_input("\n")


dictionary_attack(password_target, source_file)

1 个答案:

答案 0 :(得分:2)

您可以将此作为您的"文件不存在"异常,在打开现有文件后,您可以使用if语句检查文件中是否存在任何内容:

"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.

"""
def dictionary_attack(pass_to_be_hacked, source_file):
    try:
        txt_file = open(source_file , "r")
        if os.stat( txt_file).st_size > 0: #check if file is empty
            for line in txt_file:
                new_line = line.strip('\n')
                if new_line == pass_to_be_hacked:
                    print("\nThe password that you typed is : " + new_line + "\n")
        else:
            print "Empty file!"

    except IOError:
        print "Error: File not found!"

print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)