如何使用Python执行cURL命令? [英] How to use Python to execute a cURL command?

查看:48
本文介绍了如何使用Python执行cURL命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中执行curl命令.

I want to execute a curl command in Python.

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

Usually, I just need to enter the command in the terminal and press the return key. However, I don't know how it works in Python.

命令显示如下:

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

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

There is a request.json file to be sent to get a response.

我搜索了很多东西,感到很困惑.我尝试编写一段代码,尽管我不能完全理解它,但是它不起作用.

I searched a lot and got confused. I tried to write a piece of code, although I could not fully understand it and 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()

错误消息是 Parse Error .如何正确地从服务器获得响应?

The error message is Parse Error. How to get a response from the server correctly?

推荐答案

为简单起见,也许您应该考虑使用

For sake of simplicity, maybe you should consider using the Requests library.

带有json响应内容的示例如下:

An example with json response content would be something like:

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

如果您需要更多信息,请在快速入门部分中,他们有很多可行的示例.

If you look for further information, in the Quickstart section, they have lots of working examples.

针对特定的卷曲翻译:

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执行cURL命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆