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

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


当前回答

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

PYTHON 3

仅适用于UNIX (Linux / Mac) (!)

使用Python 3执行cURL并解析其JSON数据。

import shlex
import json
import subprocess

# Make sure that cURL has Silent mode (--silent) activated
# otherwise we receive progress data inside err message later
cURL = r"""curl -X --silent POST http://www.test.testtestest/ -d 'username=test'"""

lCmd = shlex.split(cURL) # Splits cURL into an array

p = subprocess.Popen(lCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() # Get the output and the err message

json_data = json.loads(out.decode("utf-8"))

print(json_data) # Display now the data

有时你还需要在UNIX上安装这些依赖项,如果你遇到奇怪的错误:

# Dependencies  
sudo apt install libcurl4-openssl-dev libssl-dev
sudo apt install curl

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

如果你的操作系统支持卷曲,你可以这样做:

import os

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

我用这种方式…我想你也可以用这个!

顺便说一下…当你安装python时,“os”模块会自动安装。 su,你不需要安装包;)

我有这个确切的问题,因为我必须做一些事情来检索内容,但我所拥有的只是一个旧版本的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()。