使用进度条输出

时间:2016-08-24 13:59:00

标签: python loops

我对Python非常陌生并创建了一个小密码破解程序,它使用强力攻击,我试图让我的进度条在程序运行时输出,这里是#s到目前为止我所拥有的:

import zipfile
import sys
import time


def progress_bar(sleep_time):
    for i in range(101):
        time.sleep(sleep_time)
        sys.stdout.write("\r[{0}] {1}%".format('#'*(i/10), i))
        sys.stdout.flush()


def obtain_password(path_to_zip_file):
    password = None

    zip_file = zipfile.ZipFile(path_to_zip_file)

    with open('wordlist.txt', 'r') as dict:
        for line in dict.readlines():
            possible = line.strip("\n")
            try:
                zip_file.extractall(pwd=possible)
                password = "Password found {}".format(possible)
            except:
                    pass

    return password

所以我的问题是如何在obtain_password方法运行时输出进度条?我是否需要稍微改变进度条方法?

2 个答案:

答案 0 :(得分:2)

你想要做的事情不会奏效,你必须记住你只有一个线索。

你可以做的是获取你的词汇表中的行数,并进行数学计算。顺便说一句,它肯定比计时器精确得多。

我没有对代码进行测试,但是根据这些内容,你会得到你想要的东西:

import zipfile
import sys
import time

def obtain_password(path_to_zip_file):
    password = None
    zip_file = zipfile.ZipFile(path_to_zip_file)
    with open('wordlist.txt', 'r') as f:
        lines = f.readlines()
        total = len(lines) # get number of lines
        current = 0
        for line in lines:
            current += 1
            if current % 1000 == 0: # every 1000 lines, shows the progress
                print('%.2f %%' % float(current / total * 100))
            possible = line.strip("\n")
            try:
                zip_file.extractall(pwd=possible)
                #password = "Password found {}".format(possible)
                print(possible)
                sys.exit()
            except:
                pass

另外,我建议您了解extractall引发的异常并正确捕捉它们。 抓住这样的一切:except:不是一个好习惯。

答案 1 :(得分:2)

有办法做你想做的事。

  1. 让您的密码破解者暂时更新进度条

     import time
    
     # Stores the time between updates in seconds.
     time_between_updates = 10
     last_update = 0
    
     def your_expensive_operation():
         for i in range(10000000):
             time.sleep(1)            # Emulate an expensive operation
             if time.time() - last_update > time_between_updates:
                 print("\r" + (int(i/10000000.0 * 79) * "#"), end='')
    
     your_expensive_operation()
    
  2. 使用线程

    import time
    import threading
    
    # Stores your current position in percent.
    current_position = 0
    done = False
    
    def paint_thread():
        while not done:
            print("\r" + (int(current_position * 79) * "#"), end='')
            # Make it update once a second.
            time.sleep(1)
    
    thread = threading.Thread(target=paint_thread)
    thread.start()
    
    for i in range(10000000):
         time.sleep(1)            # Emulate an expensive operation
         current_position = i/10000000.0
    
    done = True