【问题标题】:Using curl in Popen in Python在 Python 的 Popen 中使用 curl
【发布时间】:2016-07-07 20:35:00
【问题描述】:

我在 unix shell 中运行这个 curl 命令并且它可以工作(见下文)。我能够将返回的数据重定向到一个文件,但现在我想在我的代码中处理数据,而不是在文件中浪费一堆空间。

curl -k -o outputfile.txt 'obfuscatedandVeryLongAddress'
#curl command above, python representation below
addr = "obfuscatedandVeryLongAddress"
theFile = subprocess.Popen(["curl", "-k", addr], stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)

在此之后theFile.stdout 为空。 curl 命令中返回的数据应该是 4,000 行(在 shell 中运行命令时验证)。大小是否打破了 File.stdout?我做错了什么吗?我尝试使用:

out, err = theFile.communicate()

然后打印出变量,但仍然没有

编辑:格式化和澄清

【问题讨论】:

标签: python curl popen


【解决方案1】:

您需要删除shell=True

theFile = subprocess.Popen(["curl", "-k", addr], stdout = subprocess.PIPE, stderr = subprocess.PIPE)

应该可以。

如果你使用shell=True,你应该传递一个字符串。否则,您实际上正在做的是将这些参数 -kaddr 作为参数传递给 shell。所以如果你的shell是sh,那么你正在做的是sh 'curl' -k addr

【讨论】:

    【解决方案2】:

    Eugene's 是您问题的直接答案,但我想我会在使用 requests 库时添加一个,因为它需要更少的代码,并且对于需要查看您的代码的任何人来说都更容易阅读(并且具有跨平台的优势)。

    import requests
    
    response = requests.get('longaddress', verify=False)
    print response.text
    

    如果响应是json,可以自动转成python对象

    print response.json()
    

    【讨论】:

      【解决方案3】:

      您可以将 curl 命令放在如下字符串中:

      theFile = subprocess.Popen('curl -k {}'.format(addr), stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
      

      或者您可以删除 shell 参数:

      theFile = subprocess.Popen(["curl", "-k", addr], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
      

      或者您可以使用 pycurl 模块直接使用 libcurl 库并跳过整个附加过程。

      【讨论】:

        猜你喜欢
        • 2017-02-07
        • 1970-01-01
        • 2014-12-02
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-10
        • 1970-01-01
        相关资源
        最近更新 更多