【发布时间】:2014-10-18 21:49:27
【问题描述】:
我想在 Python 中执行 curl 命令。
通常,我只需要在终端中输入命令并按回车键即可。但是,我不知道它在 Python 中是如何工作的。
命令如下:
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
要发送一个request.json 文件以获得响应。
我搜索了很多并感到困惑。我试着写了一段代码,虽然我不能完全理解,也没有成功。
import pycurl
import StringIO
response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '@request.json')
c.perform()
c.close()
print response.getvalue()
response.close()
错误消息是Parse Error。如何正确获取服务器的响应?
【问题讨论】:
-
FWIW,你考虑过使用pycurl "Python binding to cURL" 吗?根据您的需要,它可能比在后台调用命令行实用程序更有效/更方便。
-
你需要使用cURL吗?你考虑过Requests吗?可能会更简单,特别是如果你是 python 新手,这往往是无情的。
-
ummm python 很宽容....也许不是 curl
-
我只想向您指出这个关于如何在 Python 中执行 shell 命令的好答案:stackoverflow.com/a/92395/778533