我想在Python中执行一个curl命令。

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

命令如下所示:

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

有一个请求。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()

错误消息是“解析错误”。如何正确地从服务器获得响应?


当前回答

使用请求库..这段代码是:

curl -LH "Accept: text/x-bibliography; style=apa" https://doi.org/10.5438/0000-0C2G

等于这个:

import requests

headers = {
    'Accept': 'text/x-bibliography; style=apa',
}

r = requests.get('https://doi.org/10.5438/0000-0C2G', headers=headers)


print(r.text)

其他回答

使用请求库..这段代码是:

curl -LH "Accept: text/x-bibliography; style=apa" https://doi.org/10.5438/0000-0C2G

等于这个:

import requests

headers = {
    'Accept': 'text/x-bibliography; style=apa',
}

r = requests.get('https://doi.org/10.5438/0000-0C2G', headers=headers)


print(r.text)

这是一种方法:

Import os
import requests 
Data = os.execute(curl URL)
R= Data.json()

我的答案是WRT 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

我很抱歉没有提供必要的参数,因为这是机密。

使用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)

为了简单起见,您应该考虑使用Requests库。

JSON响应内容的示例如下:

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

如果你想了解更多的信息,在快速入门部分,他们有很多实际的例子。

对于特定的旋度平移:

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)