如何使用python执行curl命令 [英] how to use python to execute a curl command

查看:158
本文介绍了如何使用python执行curl命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中执行curl命令。

I want to execute a curl command in python.

通常,我只需要在终端中输入命令并按回车键即可。但是,我不知道它在python中如何工作。

Usually, I just need enter the command in terminal and press return key. However, I don't know how it works in python.

命令显示如下:

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

有一个request.json文件要发送以获得响应。

There is a request.json file to be sent to get response.

我搜索了很多东西,感到很困惑。尽管我无法完全理解,但我还是尝试编写了一段代码。

I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand. It didn't work.

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()

错误消息是解析错误。谁能告诉我如何修复它?还是如何正确获取服务器的响应?

The error message is 'Parse Error'.Can anyone tell me how to fix it? or how to get response from the sever correctly?

推荐答案

为简单起见,也许您应该考虑使用请求库。

For sake of simplicity, maybe you should consider using the Requests library.

带有json响应内容的示例是

An example with json response content would be something like:

import requests
r = requests.get('https://github.com/timeline.json')
r.json()

如果您需要更多信息,请在< href = http://docs.python-requests.org/zh-CN/latest/user/quickstart/ rel = noreferrer>快速入门部分,其中有许多可行的示例。

If you look for further information, in the Quickstart section, they have lots of working examples.

编辑:

针对特定的卷曲翻译:

import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)

这篇关于如何使用python执行curl命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆