Ben*_*n K 5 python multithreading visual-studio python-requests
我已经requests在 python 2.7 中尝试过这个模块并且非常喜欢它,但是当我尝试在一个线程中使用它时,它似乎不起作用:
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()
Run Code Online (Sandbox Code Playgroud)
我试过这种方式,但它是一样的:
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()
Run Code Online (Sandbox Code Playgroud)
我试图等待几分钟(几小时),但它仍然无法正常工作;既没有after也没有错误被打印出来。我可能错过了一些东西,但我看不到什么。
我正在使用请求 2.9.1;Python 2.7.11(Anaconda 2.4.1 32 位),我在 Windows 7 上。
好的,我对此进行了深入研究并发现了问题(谁不是来自 Visual Studio)。我尝试了新项目,没有任何问题。
我知道 python 的“主”文件没有编译,所以我这样做了:
if __name__ == '__main__':
import compiled_main
Run Code Online (Sandbox Code Playgroud)
例如,其中“compiled_main”是我之前发布的代码。这样,任何使用“请求”的线程都将保持阻塞状态,请求将永远不会被执行,也永远不会引发任何异常。如果我执行 join(),我的代码将等待一个永远不会被释放的线程。
使用“.run()”有效,但它没有启动线程,我检查并注意到它只会将该方法作为经典方法调用,因此这不是解决方案。
解决方案:永远不要直接在要导入的文件中启动线程
解决方案 1:创建一个包含所有代码的 init() 方法,并像这样在 main 中调用它
if __name__ == '__main__':
import compiled_main
compiled_main.init()
Run Code Online (Sandbox Code Playgroud)
解决方案 2:直接在 main 中执行代码(真正的代码,未编译)
感谢大家的帮助,您引导我找到了解决方案(尤其是+Antti Haapala)