在Python的Popen中使用curl

在Python的Popen中使用curl,python,curl,popen,Python,Curl,Popen,我在unixshell中运行这个curl命令,它可以正常工作(见下文)。我能够将返回的数据重定向到一个文件,但现在我想在代码中处理数据,而不是在文件中浪费大量空间 curl -k -o outputfile.txt 'obfuscatedandVeryLongAddress' #curl command above, python representation below addr = "obfuscatedandVeryLongAddress" theFile = subprocess.Pop

我在unixshell中运行这个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)
在此之后,file.stdout为空。curl命令中返回的数据应该是4000行(在shell中运行命令时验证)。大小是否正在断开文件.stdout?我做错什么了吗?我尝试使用:

out, err = theFile.communicate()
然后打印出变量,但仍然是空的


编辑:格式化和澄清

您需要删除
shell=True


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

应该有用


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

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

如果响应是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库并跳过整个附加过程。

为什么不使用
请求
库?或与系统默认值
urllib
相关:
theFile = subprocess.Popen(["curl", "-k", addr], stdout = subprocess.PIPE, stderr = subprocess.PIPE)