-
Notifications
You must be signed in to change notification settings - Fork 16
/
paths.py
62 lines (47 loc) · 1.56 KB
/
paths.py
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
53
54
55
56
57
58
59
60
61
62
import os
import tempfile
from pathlib import Path
from typing import Union, TypeVar
PathStr = TypeVar("PathStr", str, Path) # type of str or Path
def rel2abs(src, *paths):
""" Output is absolute path of paths joined with src's dir
Example:
>>> rel2abs('/opt/doaj/abc.xml', 'corrections.csv')
'/opt/doaj/corrections.csv'
>>> rel2abs('/opt/doaj/', 'corrections.csv')
'/opt/doaj/corrections.csv'
>>> rel2abs('/opt/doaj/abc.xml', '..', 'corrections.csv')
'/opt/corrections.csv'
:param src:
:param paths:
:return:
"""
src = os.path.realpath(src)
if os.path.isfile(src):
src = os.path.dirname(src)
return os.path.abspath(os.path.join(src, *paths))
def list_subdirs(path):
return [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
def get_project_root() -> Path:
""" Should return folder path of `doaj` """
return Path(__file__).parent.parent.parent.absolute()
def create_tmp_dir(is_auto_mkdir=False) -> Path:
num_retry = 20
for _ in range(num_retry):
path = Path(tempfile.NamedTemporaryFile().name)
if not path.exists():
break
else:
raise EnvironmentError(f'create tmp dir retry [{num_retry}] failed')
if is_auto_mkdir:
path.mkdir(parents=True, exist_ok=True)
return path
def abs_dir_path(src: PathStr) -> str:
""" Return absolute dir path of src
Example:
>>> abs_dir_path('/opt/doaj/abc.xml')
'/opt/doaj'
>>> abs_dir_path('/opt/doaj/')
'/opt'
"""
return os.path.dirname(os.path.realpath(src))