File: utils.py

package info (click to toggle)
rednotebook 2.39%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 5,956 kB
  • sloc: python: 9,570; javascript: 4,103; xml: 128; sh: 58; makefile: 11
file content (47 lines) | stat: -rw-r--r-- 1,262 bytes parent folder | download | duplicates (3)
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
import logging
import os
import shutil
import subprocess
import sys
import urllib.request


def ensure_path(path):
    if not os.path.exists(path):
        os.mkdir(path)


def confirm_overwrite(dir):
    if os.path.exists(dir):
        answer = input(f"The directory {dir} exists. Overwrite it? (Y/n): ").strip()
        if answer and answer.lower() != "y":
            sys.exit("Aborting")
        shutil.rmtree(dir)


def fast_copytree(src_dir, dest_dir):
    subprocess.check_call(["cp", "-r", src_dir, dest_dir])


def fetch(url, path):
    dirname = os.path.dirname(path)
    if not os.path.exists(dirname):
        os.mkdir(dirname)
    if not os.path.exists(path):
        logging.info(f"Fetch {url} to {path}")
        with urllib.request.urlopen(url) as response, open(path, "wb") as out_file:
            shutil.copyfileobj(response, out_file)
    if not os.path.exists(path):
        sys.exit("Download unsuccessful.")
        sys.exit("Download unsuccessful.")


def run(*args, **kwargs):
    logging.info(f"Run command: {args} ({kwargs})")
    retcode = subprocess.call(*args, **kwargs)
    if retcode != 0:
        sys.exit("Command failed.")


def get_output(*args, **kwargs):
    return subprocess.check_output(*args, **kwargs).decode().strip()