如何克服python中的'memory error'?



我制作了一个基本的密码破解程序,它告诉用户基本的命中和试用算法可以在什么时候破解他们的密码。但是我在运行程序时遇到内存错误,我也尝试将所有数据添加到sqlite文件,但这也不起作用。请帮助我。

我的代码:

from random import *
import time
import itertools
from string import *
class password_cracker():
result = 0
pswd_db = []
def __init__(self,n):
self.n  = n
def input_phase(self):
self.n = input("Password: ")
def cracker(self):
data_stock = ascii_letters + digits + punctuation
pswd = ''
combs = list(itertools.permutations(data_stock, 6))  #I am getting the error here
start = time.time()
for byts in combs:
for bits in byts:
pswd += bits
pswd_db.append(pswd)
if pswd == self.n:
result = 1
break
else:
result = 0
pswd = ''
end = time.time()
total_time = end - start

def final_result(self):
if result == 0:
print('You have got an exceptional password!')
else:
print('Password cracked in ', total_time)
n =  password_cracker("")
n.cracker()  

在控制台中:

回溯(最近一次调用(: 文件 "c:/Users/Soumodeep Bhowmick/Desktop/CS.IP/pws.py",第 93 行,在 N.饼干(( 文件 "c:/Users/Soumodeep Bhowmick/Desktop/CS.IP/pws.py",第 59 行,在饼干中 combs = list(itertools.permutations(data_stock, 6(( 内存错误

在那一行:

combs = list(itertools.permutations(data_stock, 6))

您要求提供所有长度为 6 种排列的data_stock(长度为 94 个字符(的列表。所以,这是一个 94 ^ 6(或 94!/88!,如果你期望组合(字符串的列表,长度为 6 个字符。或者,简单地说,包含 689,869,781,056 或 586,236,072,240 个 6 个字符的字符串的列表。

如果您改用迭代器,则不会耗尽内存,但您的脚本会忙一段时间...您可能需要完全考虑另一种方法。

list调用将整个 6 元素字符串列表放入内存中。您应该能够删除list调用:

combs = itertools.permutations(data_stock, 6)
for comb in combs:
...

这将仅在需要时生成每个排列 - 一次只会在内存中存储一个排列。根据经验,itertools 模块中的内容自然会返回迭代器,这些迭代器旨在供 for 循环使用。

相关内容

最新更新