首页 > 解决方案 > Python 3 中带有选项的 curl 命令

问题描述

requests库中,如果需要执行

curl http://www.example.com/file.xlsx

命令是

response = requests.get('http://www.example.com/file.xlsx')

如果我想使用-O选项执行命令怎么办?

curl http://www.example.com/file.xlsx -O

我该如何做到这一点?

标签: pythonpython-3.x

解决方案


没有明确的“-O”=写入相同的文件名。如果需要,可以将 url 存储在变量中并使用多种获取方式。一种懒惰的方式是rpartition('/')[2]在 url 字符串上使用。

其余快速保存结果的代码在这里:

import requests
from pathlib import Path

response = requests.get('http://www.example.com/file.xlsx')
Path('file.xlsx').write_bytes(response.content)

# or if you want to have the file name extracted use this less readable line
# Path(response.url.rpartition('/')[2]).write_bytes(response.content)

推荐阅读