如何使用Python执行cURL命令?

如何使用Python执行cURL命令?,python,curl,Python,Curl,我想在Python中执行curl命令 通常,我只需要在终端中输入命令并按下返回键。然而,我不知道它在Python中是如何工作的 该命令显示如下: curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere 有一个request.json文件要发送以获取响应 我找了很多,弄糊

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

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? 

为了简单起见,也许你应该考虑使用这个库。

包含json响应内容的示例如下:

import requests
r = requests.get('https://github.com/timeline.json')
r.json()
如果您想了解更多信息,在本节中,他们提供了很多工作示例

编辑:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf
对于特定的卷曲翻译:

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实现类似于

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)

检查,它将帮助将cURl命令转换为python、php和nodejs我的答案是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

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

这可以通过下面提到的psuedo代码方法实现

导入操作系统 导入请求 Data=os.execute(curl URL) R=Data.json()。它将把任何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

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

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

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)

一些背景:我一直在寻找这个问题,因为我必须做一些事情来检索内容,但我所能得到的只是一个旧版本的python,没有足够的SSL支持。如果你用的是旧版的MacBook,你知道我在说什么。在任何情况下,
curl
都可以在shell中正常运行(我怀疑它链接了现代SSL支持),因此有时您希望在不使用
请求
urllib2
的情况下执行此操作

您可以使用
子流程
模块执行
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])


Python3的
子流程
模块还包含
.run()
,以及许多有用的选项。我将把这个问题留给实际运行python 3的人来回答。

我使用
os

import os

os.system("sh script.sh")

script.sh
字面上只包含curl。

Python3

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

使用Python3执行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

这有用吗?FWIW,您考虑过使用“Python绑定到cURL”吗?根据您的需要,它可能比在后台调用命令行实用程序更高效/方便。您需要使用cURL吗?你考虑过吗?可能更简单,尤其是如果您是python新手,这往往是不可原谅的。。。。也许不是,我只是想告诉你一个关于如何在Python中执行shell命令的好答案:它不包括来自
requests.json
文件的数据,也不设置
内容类型:application/json
头-而且,这将发送
GET
请求,不是
POST
curl-d@
会从
读取要发布的字段-这与文件上载不同。@LukasGraf谢谢:)。。。我不经常使用curl(阅读:几乎从不使用)一个小注释,
data=requests.get(url.json
应该是
data=requests.get(url.json()
在2014年,它现在是一个属性,它是一个函数:)好的调用thoughPlease@tricknology,尝试搜索bug,如果你没有找到合适的解决方案,发布一个新问题。如果其他人碰巧看到了这一点,我之所以会遇到这种情况,是因为我提供了一个字符串作为有效负载,而不是字典对象。标题中似乎有一个小的拼写错误,在发送之前打开文件并解析JSON是毫无必要的低效的。解析JSON,然后使用JSON.dumps()将其转换回字符串。这是一个错误的答案。
请求
是您需要安装和管理的额外依赖项。对于只使用标准库的简单解决方案,请参见os.system而不是os.execute,在这种情况下,如果需要使用curl中的一些特殊选项,则请求似乎是不必要的,例如--resolve这就是解决方法。谢谢。我如何才能在没有表格的情况下仅获取返回的json以确保json格式正确?导入“json”模块并在数据有效负载上使用json.dumps(有效负载),即在上述情况下,data=json.dumps(数据)