gpt4 book ai didi

Python - 我如何保存 itertools.product 循环并从它停止的地方恢复

转载 作者:行者123 更新时间:2023-12-05 00:49:58 25 4
gpt4 key购买 nike

我正在编写一个 python 脚本来基本上检查每个可能的 url 并在它响应请求时记录它。

我在 StackOverflow 上找到了一篇文章,其中提出了一种为 url 生成字符串的方法,效果很好。

    for n in range(1, 4 + 1):
for comb in product(chars, repeat=n):
url = ("http://" + ''.join(comb) + ".com")
currentUrl = url
checkUrl(url)

正如您可以想象的那样,有很多 url 的方法,这将花费很长时间,所以我试图找到一种方法来保存我的脚本并从它停止的情况下恢复。

我的问题是如何让循环从特定位置开始,或者是否有人有一段工作代码可以做同样的事情并允许我在起点指定。

到目前为止,这是我的脚本..
import urllib.request
from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product

goodUrls = "Valid_urls.txt"
saveFile = "save.txt"
currentUrl = ''


def checkUrl(url):
print("Trying - "+url)
try:
urllib.request.urlopen(url)
except Exception as e:
None
else:
log = open(goodUrls, 'a')
log.write(url + '\n')



chars = digits + ascii_lowercase

try:
while True:
for n in range(1, 4 + 1):
for comb in product(chars, repeat=n):
url = ("http://" + ''.join(comb) + ".com")
currentUrl = url
checkUrl(url)
except KeyboardInterrupt:
print("Saving and Exiting")
open(saveFile,'w').write(currentUrl)

最佳答案

itertools.product的返回值是一个生成器对象。因此,您所要做的就是:

products = product(...)

for foo in products:
if bar(foo):
spam(foo)
break
# other stuff

for foo in products:
# starts where you left off.

在您的情况下,迭代可能性所需的时间非常少,至少与发出所有这些网络请求所需的时间相比。您可以将所有可能性保存到磁盘并转储每次程序运行后剩余内容的列表,或者您可以只保存您所在的号码。自 product具有确定性输出,应该这样做。
try:
with open("progress.txt") as f:
first_up = int(f.read().strip())
except FileNotFoundError:
first_up = 0
try:
for i, foo in enumerate(products):
if i <= first_up:
continue # skip this iteration
# do stuff down here
except KeyboardInterrupt:
# this is really rude to do, by the by....
print("Saving and exiting"
with open("progress.txt", "w") as f:
f.write(str(i))

如果出于某种原因您需要一个人类可读的“进度”文件,您可以像上面一样保存您的最后一个密码并执行以下操作:
for foo in itertools.dropwhile(products, lambda p != saved_password):
# do stuff

关于Python - 我如何保存 itertools.product 循环并从它停止的地方恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com