python - 泳池系统错误
问题描述
我正在尝试将池系统添加到我的应用程序中,但我认为我做错了什么。
我的代码:
import requests, threading, platform, os
from multiprocessing.dummy import Pool
if platform.system() == "Linux":
clear = lambda: os.system('clear')
clear()
if platform.system() == "Windows":
clear = lambda: os.system('cls')
clear()
def check(data):
try:
r = requests.get(data)
if 'working ' in r.text:
with open("working.txt", mode="a") as urlsvuln:
print("Working : " + r.url)
urlsvuln.write(r.url + "\n")
else:
print("Not working")
except Exception as e:
print(e)
with open("texte.txt", mode="r") as mf:
lines = mf.read().splitlines()
for line in lines:
data = line + "'"
print(data)
try:
pp = Pool(10)
pr = pp.map(check, data)
except Exception as e:
print(e)
所以这段代码可以正常工作,但我可以看到我是否有一个包含 3 行的文本文件来查看 url 是否正常工作,并且我看到我的应用程序正在执行 10 次请求,并且在我的文本中写入 10 倍。
解决方案
我认为这将实现您正在尝试做的事情
import requests, platform, os
from multiprocessing.dummy import Pool
from io import StringIO
if platform.system() == "Linux":
clear = lambda: os.system('clear')
clear()
if platform.system() == "Windows":
clear = lambda: os.system('cls')
clear()
def check(data):
try:
r = requests.get(data, timeout=2)
if r.text:
out.write(f"Working {data}\n")
else:
out.write(f"Not working {data}\n")
except Exception as e:
out.write(f"Not working {data}\n")
urls = StringIO("https://www.google.com\nhttps://www.yahoo.com\nhttps://www.nonexistent.com")
# Note I am using in-memory file here but you can read the urls from file here
data = urls.read().splitlines()
try:
with open("working.txt", mode="a") as out:
pp = Pool(10)
pr = pp.map(check, data)
except Exception as e:
print(e)
虽然multiprocessing.dummy.Pool
在这里完成了工作,但我强烈建议ThreadPoolExecutor
在这里使用以使其无阻塞。
推荐阅读
- rest - Sonos Cloud API HTTP POST 始终返回 500
- python - 对列求和的 TF-IDF 矩阵中零的含义
- android - Flutter 中的无边框选择高亮效果
- wordpress - 陷阱尝试在没有收件人的情况下发送 Woocommerce 邮件:
- reactjs - 如何实现 instagram 故事线性渐变 react native
- racket - 如何打印自定义对象?
- c - QEMU 中向 CPU 提供定时器
- c++ - 我的代码不断返回 0 作为文本文件中的小数位数
- python-3.x - 这种使用skip-gram的文本训练是否正确?
- java - 如何使用 Java EE Security 从 HttpSessionListener 访问登录的主体?