如何使用 Python 执行 cURL 命令? [英] How to use Python to execute a cURL command?

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

问题描述

我想在 Python 中执行 curl 命令.

I want to execute a curl command in Python.

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

Usually, I just need to enter the command in the terminal and press the 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 a response.

我搜索了很多,但很困惑.我试着写了一段代码,虽然我不能完全理解它,它没有工作.

I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand it and 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()

错误信息是Parse Error.如何正确得到服务器的响应?

The error message is Parse Error. How to get a response from the server 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()

如果您想了解更多信息,请在快速入门部分,他们有很多工作示例.

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

对于您的特定卷曲翻译:

For your specific curl translation:

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天全站免登陆