Curl command with options in Python 3

Viewed 248

In requests library, if you need to execute

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

The command is

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

What If I want to execute the command with -O option?

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

How do I achieve that?

3 Answers

There's no explicit "-O" = write to the same filename. You if you need that, you can store the url in a variable and use several ways of getting it. A lazy way is using rpartition('/')[2] on the url string.

The rest of the code to quickly save the result is here:

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)

To achieve the use case of CURL's -O option in Python, you have to write few lines of code like,

import requests
r = requests.get('https://your.url.com/path')

with open('path.txt','w') as fd:
    fd.write(r.text)

I'm not sure requests supports a flag for this purpose. However, you can try doing something like:

from pathlib import Path

p = Path('http://www.example.com/file.xlsx')
r = requests.get(str(p))
Path(p.name).write_bytes(r.content)
Related