【问题标题】:CURL request to Python as command line对 Python 的 CURL 请求作为命令行
【发布时间】:2018-06-15 08:08:41
【问题描述】:

目前,我正在尝试将 CURL 请求转换为 Python 脚本。

curl $(curl -u username:password -s https://api.example.com/v1.1/reports/11111?fields=download | jq ".report.download" -r) > "C:\sample.zip"

我试过pycurl,由于知识有限,没有成功。

作为一种解决方案,我发现可以通过 python 运行命令。 https://www.raspberrypi.org/forums/viewtopic.php?t=112351

import os
os.system("curl -K.........")

和其他解决方案(基于搜索更常见)使用子进程

import subprocess

subprocess.call(['command', 'argument'])

目前,我不确定要搬到哪里以及如何使此解决方案适应我的位置。

import os

os.system("curl $(curl -u username:password -s https://api.example.com/v1.1/reports/11111?fields=download | jq '.report.download' -r) > 'C:\sample.zip'")

'curl' is not recognized as an internal or external command,
operable program or batch file.
255

附注- 更新 v1

有什么建议吗?

import requests

response = requests.get('https://api.example.com/v1.1/reports/11111?fields=download | jq ".report.download" -r', auth=('username', 'password'))

本作品没有“| jq ".report.download”这部分,但这是主要部分,最后只给出了下载文件的链接。

有什么办法吗?

【问题讨论】:

  • requests 模块应该可以帮助你
  • curl 可执行文件不在PATH 环境变量中,尝试将curl 添加到路径或使用apt 从apt 安装它
  • @Rakesh 已更新(请查看)
  • @sriharsha_bhat 有潜力,但当我尝试使用 JQ 时出现问题。
  • @Rakesh 看,请求确实有效,但管道后的 jq 部分不起作用,这给了我而不是完整的 JSON,只是它的内容,有什么建议吗???

标签: python curl subprocess pycurl


【解决方案1】:

错误'curl' is not recognized as an internal or external command表示python找不到安装curl的位置。如果您已经安装了 curl,请尝试提供安装 curl 的完整路径。例如,如果 curl.exe 位于 C:\System32,则 try

import os

os.system("C:\System32\curl $(curl -u username:password -s https://api.example.com/v1.1/reports/11111?fields=download | jq '.report.download' -r) > 'C:\sample.zip'")

但这绝对不是pythonic的做事方式。我会建议使用requests 模块。 为此,您需要调用 requests 模块两次,首先从 https://api.example.com/v1.1/reports/11111?fields=download 下载 json 内容,获取report.download 指向的新 url,然后再次调用 requests 从新 url 下载数据。

这些方面的东西应该会让你继续前进

import requests

url        = 'https://api.example.com/v1.1/reports/11111'
response   = requests.get(url, params=(('fields', 'download'),),
                          auth=('username', 'password'))

report_url = response.json()['report']['download']
data = requests.get(report_url).content

with open('C:\sample.zip', 'w') as f:
    f.write(data)

【讨论】:

  • 感谢您的帮助,非常感谢。
【解决方案2】:

您可以使用此站点将命令的实际 curl 部分转换为适用于请求的内容:https://curl.trillworks.com/

从那里,只需使用请求对象的.json() 方法来执行您需要执行的任何处理。

终于可以这样保存了:

import json
with open('C:\sample.zip', 'r') as f:
    json.dump(data, f)

【讨论】:

  • 这是我用来转换其他部分的网站,但是这个特定的部分,我还不能转换。
猜你喜欢
  • 2020-10-01
  • 2018-10-21
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 2020-08-15
  • 2017-07-12
  • 1970-01-01
相关资源
最近更新 更多