gpt4 book ai didi

Python "requests"在线程中不工作/阻塞?

转载 作者:行者123 更新时间:2023-11-28 19:13:46 25 4
gpt4 key购买 nike

我在 python 2.7 中尝试过 requests 模块并且非常喜欢它,但是当我尝试在线程中使用它时,它似乎不起作用:

def doWork():
try:
print "before"
requests.get('http://www.google.fr')
print "after"
except Exception as e:
print "Error : "+ str(e)

# Working : I see "before" & "after"
doWork()

# Not working, i see "before" but never "after"
t = Thread(target=doWork)
t.start()

我试过这种方式,但它是一样的:

class TestThread(Thread):
def run(self):
try:
print "before"
requests.get('http://www.google.fr')
print "after"
except Exception as e:
print "Error : "+ str(e)

test_thread = TestThread()
test_thread.start() # I will see "before" but never "after"
test_thread.join()

我试着等了几分钟(几小时),但还是不行; after 和错误都不会打印出来。我可能错过了什么,但我看不到什么。

我正在使用 Requests 2.9.1; Python 2.7.11( python 2.4.1 32 位)我在 Windows 7 上。

最佳答案

好的,我对此进行了深入研究并发现了问题(谁不是来自 visual studio)。我尝试了新项目,没有遇到任何问题。

我知道 python 的“主”文件没有编译,所以我这样做了:

if __name__ == '__main__':
import compiled_main

例如,“compiled_main”是我之前发布的代码。这样,任何使用“请求”的线程都将保持阻塞状态,请求将永远不会被执行,也永远不会引发任何异常。如果我执行 join(),我的代码将等待一个永远不会被释放的线程。

使用“.run()”有效,但它没有启动线程,我检查并注意到只会将方法作为经典方法调用,所以这不是解决方案。

解决方案:切勿直接在要导入的文件中启动线程

解决方案 1:创建一个包含所有代码的 init() 方法,并像这样在 main 中调用它

if __name__ == '__main__':
import compiled_main
compiled_main.init()

解决方案 2:直接在您的 main 中执行您的代码(真实的,未编译的)

感谢大家的帮助,您引导我找到了解决方案(尤其是 +Antti Haapala)

关于Python "requests"在线程中不工作/阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36214695/

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