我想在Python中执行一个curl命令。
通常,我只需要在终端中输入命令,然后按return键。但是,我不知道它在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
。如何正确获取来自服务器的响应?
发布于 2014-08-26 01:28:07
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?
发布于 2018-03-16 00:41:27
我的答案是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
我很抱歉没有提供所需的参数,因为这是保密的。
发布于 2019-07-08 04:58:23
一些背景知识:我去寻找这个问题,因为我必须做一些事情来检索内容,但我只有一个旧版本的python,没有足够的SSL支持。如果你用的是老的MacBook,你知道我在说什么。在任何情况下,curl
都可以在shell中运行良好(我怀疑它链接了现代的SSL支持),所以有时您不希望使用requests
或urllib2
。
您可以使用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])
Python3的subprocess
模块还包含带有许多有用选项的.run()
。我将把这个问题留给真正运行python3的人来回答。
https://stackoverflow.com/questions/25491090
复制相似问题