python - 在完成循环之前执行 for 循环之后的代码
问题描述
我一直在搜索,但我找不到我的代码有什么问题。它是一个代理检查器,我用线程制作了一个 for 循环,并希望它在完成循环后打印“FINISHED”:
def cthread():
while len(proxies) > 0:
proxy = proxies.pop(0)
try:
requests.get(url, proxies={'https':proxytype+"://"+proxy}, timeout=timeout)
print(proxy, '< GOOD PROXY')
with open('working.txt', 'a') as proxywork:
proxywork.write(proxy + '\n')
proxywork.flush()
except:
try:
print(proxy, ' > BAD')
except:
print("ERROR")
for i in range(tc):
threading.Thread(target=cthread).start()
configuration.close()
print("FINISHED")
time.sleep(900.0 - ((time.time() - starttime) % 900.0))
但它甚至在检查一半代理之前打印“完成”,我希望它在完成 for 循环后这样做。
感谢您的帮助:)
解决方案
在循环启动每个线程后,您需要加入每个线程以等待它完成。
threads = [threading.Thread(target=cthread) for _ in range(tc)]
for t in threads:
t.start()
# Do stuff here while threads are running
# Now wait for all threads to complete
for t in threads:
t.join()
configuration.close()
print("FINISHED")
time.sleep(900.0 - ((time.time() - starttime) % 900.0))
推荐阅读
- android - TextView 出现在预览中,但不在模拟器和真实设备上
- javascript - Chrome 需要很长时间才能元刷新非活动页面
- sympy - sympy 将分数与变量分开
- c - 基本 VLDR 上的 STM32 Cortex-M4F FPU 硬故障
- linux - 如何从日志文件中grep特定错误及其多行描述并将其输出到Linux中的新日志文件中?
- css - 如何链接使用伪添加的文本:列表中的类之前
- python - 使用 Python、Kubernetes api 调用的 YAML 到 JSON
- c++ - Cpp uint32_fast_t 解析为 uint64_t,但几乎所有操作都比 uint32_t (x86_64) 慢。为什么它解析为 uint64_t?
- reactjs - 如何导出带有相关“子”组件的 React 组件
- r - 开箱即用的功能将关卡的长尾放置在一个功能中作为“其他”?