Skip to content

Instantly share code, notes, and snippets.

@mezhgano
Last active March 25, 2023 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mezhgano/33ff01e3d71e2ae1eb30057646d59657 to your computer and use it in GitHub Desktop.
Save mezhgano/33ff01e3d71e2ae1eb30057646d59657 to your computer and use it in GitHub Desktop.
Script to set download path
import os
import sys
from pathlib import Path
from typing import List, Optional
def _exit(message: str, status=0):
'Gracefully exit with status code and message to stderr.'
if status != 0:
sys.stderr.write(message)
raise SystemExit(status)
def set_download_path(path: Optional[str] = None) -> Path:
'''
Perform several sanity checks against given path (in string), exit if at least one check are not passed.
Return PurePath object from given path, if path is None return PurePath object from current working directory.
'''
if not path:
dest_dir = Path.cwd().resolve()
else:
_path = Path(path)
message = ('Given path is not {reason}.\n'
'Please specify different path or not specify path at all '
'to download to current directory.')
if not Path.exists(_path):
_exit(message.format(reason = 'exist'), 1)
elif not Path.is_dir(_path):
_exit(message.format(reason = 'a folder'), 1)
elif not os.access(_path, os.W_OK):
_exit(message.format(reason = 'writable'), 1)
else:
dest_dir = _path
return dest_dir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment