如何使用python执行curl命令

how to use python to execute a curl command

我想在python中执行curl命令。

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

该命令显示如下:

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

有一个request.json文件要发送以获得响应。

我搜索了很多,感到困惑。 尽管我无法完全理解,但我尝试编写一段代码。 没用

1
2
3
4
5
6
7
8
9
10
11
12
13
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响应内容的示例如下所示:

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

如果您需要更多信息,请在"快速入门"部分中找到许多可行的示例。

编辑:

对于您特定的curl翻译:

1
2
3
4
5
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)


只需使用此网站。它将任何curl命令转换为Python,Node.js,PHP,R或Go。

例:

1
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

在Python中成为这个

1
2
3
4
5
6
7
8
9
import requests

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

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

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


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

它的python实现就像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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


1
2
3
import requests
url ="https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

也许?

如果您要发送文件

1
2
3
files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

啊,谢谢@LukasGraf现在,我更好地了解了他的原始代码在做什么

1
2
3
4
5
6
7
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?


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


我的答案是WRT python 2.6.2。

1
2
3
4
5
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

很抱歉没有提供所需的参数,因为这是机密信息。


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

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

1
2
3
4
5
6
7
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的subprocess模块还包含带有许多有用选项的.run()。我将其留给实际上正在运行python 3的人提供该答案。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)

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

导入操作系统
汇入要求
数据= os.execute(curl URL)
R = Data.json()