-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimg-download
executable file
·52 lines (40 loc) · 1.25 KB
/
img-download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
import os
import sys
import tempfile
from urllib.parse import urlparse
import requests
import click
from pura import clipboard
def url_filename(url: str) -> str:
# get the basename of the path of the URL
# ignoring any params/query/fragment
f = os.path.basename(urlparse(url).path)
if f.strip():
return f
return "image"
@click.command()
@click.argument("URL", default=clipboard.clippaste().strip())
def main(url) -> None:
"""
\b
downloads an image to your tmpdir, moves it so that the extension is valid
prints the path its downloaded to and puts the path on your clipboard
"""
if url == "":
click.echo("No content on your clipboard!", err=True)
sys.exit(1)
# probably ran twice and the URL is already downloaded?
# leave the path on my clipboard as is
if not os.path.exists(url):
r = requests.get(url, stream=True)
assert r.status_code == 200
tmpdir: str = tempfile.mkdtemp()
write_to = os.path.join(tmpdir, url_filename(url))
with open(write_to, "wb") as f:
for chunk in r:
f.write(chunk)
clipboard.clipcopy(write_to)
click.echo(write_to)
if __name__ == "__main__":
main()