-
Notifications
You must be signed in to change notification settings - Fork 12
/
util.py
60 lines (51 loc) · 1.69 KB
/
util.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
import logging
import sys
import urllib.request
from typing import Union
log = logging.getLogger(__name__)
def looks_like_url(path: str):
url_starts = ["http://", "https://"]
return any(path.startswith(x) for x in url_starts)
def write_output(path: str, content: str) -> bool:
if path == 'STDOUT':
log.info(f'Writing to stdout.')
sys.stdout.write(content)
sys.stdout.flush()
return True
else:
log.info(f'Writing file "{path}".')
with open(path, "w") as f:
try:
f.write(content)
return True
except PermissionError:
log.error(f'No permission to open "{path}".')
return False
except IsADirectoryError:
log.error(f'Cannot open directory "{path}".')
return False
except IOError:
log.exception(f'Error writing file "{path}".')
return False
def read_input(path: str) -> Union[str, None]:
if path == 'STDIN':
return sys.stdin.read()
elif looks_like_url(path):
with urllib.request.urlopen(path) as f:
content = f.read().decode()
return content
else:
log.info(f'Reading file "{path}".')
try:
with open(path, "r") as f:
content = f.read()
return content
except PermissionError:
log.error(f'No permission to open "{path}".')
return None
except IsADirectoryError:
log.error(f'Cannot open directory "{path}".')
return None
except IOError:
log.exception(f'Error reading file "{path}".')
return None