简体   繁体   English

Requests.get()卡在连接上

[英]Requests.get() gets stuck on connect

I'm trying to make a simple get request using requests 我正在尝试使用requests提出一个简单的获取requests

import requests

def main():
    content = requests.get("https://google.com")
    print(content.status_code)

if __name__ == "__main__":
    main()

I'm running this on Linux, version 17.10. 我正在Linux 17.10版上运行它。 Python version: either 2.7 or 3.6 (tried both). Python版本:2.7或3.6(都尝试过)。

The code gets stuck in running, it doesn't timeout or anything. 代码卡在运行中,不会超时或其他任何原因。

After I stop it, based on the callstack, it gets stuck at: 在我停止它之后,基于调用栈,它陷入了:

File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args)

I just ran your code on Python console and it returned 200 . 我只是在Python控制台上运行了您的代码,它返回了200 I am Running Python 3.6.7, Ubuntu 18.04. 我正在运行Python 3.6.7,Ubuntu 18.04。

It may be the case that your computer cannot connect to google.com for a very long time, you should pass timeout parameter along with try except 可能是您的计算机长时间无法连接到google.com,您应该将timeout参数与try except一起传递, try except

Use the following code: 使用以下代码:

import requests

def main():
    success = False
    while success==False:
        try:
            content = requests.get("https://google.com", timeout=5)
            success=True
        except:
            pass
    print(content.status_code)

if __name__ == "__main__":
    main()

If there is a temporary problem with your network connection, this code snippet gurantees a proper response. 如果您的网络连接出现暂时性问题,则此代码段可确保正确响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM