如何使用python执行curl命令

Qia*_* Fu 135 python curl

我想在python中执行curl命令.

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

该命令如下所示:

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

有一个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()
Run Code Online (Sandbox Code Playgroud)

错误信息是'Parse Error'.任何人都可以告诉我如何修复它?或者如何正确地从服务器获得响应?

oto*_*las 154

为简单起见,您可以考虑使用标准库 请求.

json响应内容的示例如下:

import requests
r = requests.get('https://github.com/timeline.json')
r.json()
Run Code Online (Sandbox Code Playgroud)

如果您要查找更多信息,请在" 快速入门"部分中找到许多有用的示例.

编辑:

对于您的特定卷曲翻译:

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)
Run Code Online (Sandbox Code Playgroud)

  • "请求"是您需要安装和管理的额外依赖项.有关仅使用标准库的简单解决方案,请参阅/sf/answers/974535131/ (4认同)
  • 如果其他任何人碰巧看到这一点,那么发生在我身上的原因是我给了一个字符串作为我的有效负载而不是字典对象. (2认同)

Kyl*_*ine 64

只需使用这个网站.它会将任何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
Run Code Online (Sandbox Code Playgroud)

在Python中成为现实,

import requests

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

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)
Run Code Online (Sandbox Code Playgroud)

  • 为了确保您的JSON格式正确,请导入“ json”模块,并在数据有效载荷上使用json.dumps(payload),即上述情况下的data = json.dumps(data) (3认同)

Jor*_*ley 18

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

也许?

如果您要发送文件

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

啊,谢谢@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? 
Run Code Online (Sandbox Code Playgroud)

  • 一个小注释,`data = requests.get(url).json` 应该是 `data = requests.get(url).json()` (2认同)

cry*_*KTM 18

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

它的python实现就像

import requests

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

params = (
    ('key', 'mykeyhere'),
)

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

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
Run Code Online (Sandbox Code Playgroud)

检查此链接,它将帮助将cURl命令转换为python,php和nodejs


小智 12

我的答案是 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
Run Code Online (Sandbox Code Playgroud)

我很抱歉没有提供所需的参数,因为它是机密的。


joe*_*eus 10

一些背景:我一直在寻找这个问题,因为我必须做一些事情来检索内容,但我所拥有的只是一个旧版本的 python,SSL 支持不足。如果您使用的是较旧的 MacBook,就会知道我在说什么。在任何情况下,curl从 shell 运行良好(我怀疑它链接了现代 SSL 支持)所以有时你想不使用requestsurllib2.

您可以使用该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])

Run Code Online (Sandbox Code Playgroud)

Python 3 的subprocess模块还包含.run()许多有用的选项。我会把它留给实际运行 python 3 的人来提供答案。


Edg*_*yan 9

有一个不错的网站https://curl.trillworks.com/为您完成转换。它确实从cURL转换为Python,Node.js,R,PHP,Go。


Jac*_*ead 5

我使用os图书馆。

import os

os.system("sh script.sh")
Run Code Online (Sandbox Code Playgroud)

script.sh实际上只包含卷曲。