Python urllib2 force IPv4

前端 未结 2 1937
夕颜
夕颜 2021-01-18 06:55

I am running a script using python that uses urllib2 to grab data from a weather api and display it on screen. I have had the problem that when I query the server, I get a \

2条回答
  •  误落风尘
    2021-01-18 07:20

    Not a proper answer but an alternative: call curl?

    import subprocess
    import sys
    
    def log_error(msg):
        sys.stderr.write(msg + '\n')
    
    def curl(url):
        process = subprocess.Popen(
            ["curl", "-fsSkL4", url],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        stdout, stderr = process.communicate()
        if process.returncode == 0:
            return stdout
        else:
            log_error("Failed to fetch: %s" % url)
            log_error(stderr)
            exit(3)
    

提交回复
热议问题