我想在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()

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


当前回答

为了简单起见,您应该考虑使用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)

其他回答

我使用os库。

import os

os.system("sh script.sh")

Script.sh字面上只包含curl。

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

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

为了简单起见,您应该考虑使用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)

我有这个确切的问题,因为我必须做一些事情来检索内容,但我所拥有的只是一个旧版本的Python,它对SSL的支持不足。如果你用的是老式MacBook,你就知道我在说什么了。在任何情况下,curl在shell中运行都很好(我怀疑它链接了现代SSL支持),因此有时您希望在不使用请求或urllib.request的情况下做到这一点。

你可以使用subprocess模块来执行curl并获取检索到的内容:

import subprocess

# 'response' contains a []byte with the retrieved content.
# use '-s' to keep curl quiet while it does its job, but
# it's useful to omit that while you're still writing code
# so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])

Python 3的子进程模块也包含带有许多有用选项的.run()。