如何使用python执行curl命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25491090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use python to execute a curl command
提问by Qiang Fu
I want to execute a curl command in python.
我想在 python 中执行 curl 命令。
Usually, I just need enter the command in terminal and press return key. However, I don't know how it works in python.
通常,我只需要在终端中输入命令并按回车键。但是,我不知道它在 python 中是如何工作的。
The command shows below:
命令显示如下:
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
There is a request.json file to be sent to get response.
有一个 request.json 文件要发送以获得响应。
I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand. It didn't work.
我搜索了很多并感到困惑。我试着写了一段代码,虽然我不能完全理解。它没有用。
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()
The error message is 'Parse Error'.Can anyone tell me how to fix it? or how to get response from the sever correctly?
错误消息是“解析错误”。谁能告诉我如何修复它?或者如何正确获得服务器的响应?
回答by Joran Beasley
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json
maybe?
也许?
if you are trying to send a file
如果您正在尝试发送文件
files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json
ahh thanks @LukasGraf now i better understand what his original code is doing
啊谢谢@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?
回答by otorrillas
For sake of simplicity, maybe you should consider using the Requestslibrary.
为简单起见,也许您应该考虑使用Requests库。
An example with json response content would be something like:
带有 json 响应内容的示例类似于:
import requests
r = requests.get('https://github.com/timeline.json')
r.json()
If you look for further information, in the Quickstartsection, they have lots of working examples.
如果您想了解更多信息,在快速入门部分,他们有很多工作示例。
EDIT:
编辑:
For your specific curl translation:
对于您的特定卷曲翻译:
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)
回答by cryptoKTM
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
its python implementation be like
它的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)
check this link, it will help convert cURl command to python,php and nodejs
检查此链接,它将有助于将 cURl 命令转换为 python、php 和 nodejs
回答by apoorva_bhat
My answer is WRT python 2.6.2.
我的答案是 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
I apologize for not providing the required parameters 'coz it's confidential.
我很抱歉没有提供所需的参数,因为它是机密的。
回答by user9761315
This could be achieve with the below mentioned psuedo code approach
这可以通过下面提到的伪代码方法来实现
Import os import requests Data = os.execute(curl URL) R= Data.json()
导入 os 导入请求 Data = os.execute(curl URL) R= Data.json()
回答by Kyle Bridenstine
Just use this website. It'll convert any curl command into Python, Node.js, PHP, R, or Go.
只要使用这个网站。它会将任何 curl 命令转换为 Python、Node.js、PHP、R 或 Go。
Example:
例子:
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf
Becomes this in Python,
在 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)
回答by joemadeus
Some background: I went looking for exactly this question because I had to do something to retrieve content, but all I had available was an old version of python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curlruns fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requestsor urllib2.
一些背景:我一直在寻找这个问题,因为我必须做一些事情来检索内容,但我所拥有的只是一个旧版本的 python,SSL 支持不足。如果您使用的是较旧的 MacBook,就会知道我在说什么。在任何情况下,curl从 shell 运行良好(我怀疑它链接了现代 SSL 支持)所以有时你想不使用requests或urllib2.
You can use the subprocessmodule to execute curland get at the retrieved content:
您可以使用该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's subprocessmodule also contains .run()with a number of useful options. I'll leave it to someone who is actually running python 3 to provide that answer.
Python 3 的subprocess模块还包含.run()许多有用的选项。我会把它留给实际运行 python 3 的人来提供答案。

