如何用Python执行cURL命令?

292 投票
12 回答
920227 浏览
提问于 2025-04-18 18:28

我想在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。我该如何正确地从服务器获取响应呢?

12 个回答

15

我的回答是关于Python 2.6.2的。

import commands

status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")

print output

我很抱歉没有提供所需的参数,因为这些信息是保密的。

28
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

可能吧?

如果你是想发送一个文件的话

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

啊,谢谢@LukasGraf,现在我更明白他原来的代码在做什么了

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 
38
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

它的Python实现看起来是这样的:

import requests

headers = {
    'Content-Type': 'application/json',
}

params = {
    'key': 'mykeyhere',
}

with open('request.json') as f:
    data = f.read().replace('\n', '')

response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', params=params, headers=headers, data=data)

查看这个链接,它可以帮助你把cURL命令转换成Python、PHP和Node.js代码。

199

可以使用 curlconverter.com 这个网站。它可以把几乎所有的 curl 命令转换成 Python、Node.js、PHP、R、Go 等多种编程语言的代码。

举个例子:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

在 Python 中会变成这样

import requests

json_data = {
    'text': 'Hello, World!',
}

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', json=json_data)
325

为了简单起见,你可以考虑使用Requests这个库。

一个处理JSON响应内容的例子可能是这样的:

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

如果你想了解更多信息,可以去快速入门部分,那里面有很多实际的例子。

关于你特定的curl转换:

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)

撰写回答