在 Python 的 Popen 中使用 curl

Using curl in Popen in Python

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

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 中执行命令时验证)。尺寸突破theFile.stdout了吗?我做错了什么吗?我尝试使用:

out, err = theFile.communicate()

然后打印输出变量,但仍然没有任何结果

编辑:格式和说明

您需要删除 shell=True

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

应该可以。

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

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

import requests

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

如果响应是json,您可以自动将其转换为python对象

print response.json()

您可以将 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库,跳过整个额外的过程。