forked from scito/extract_otp_secrets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
98 lines (73 loc) · 2.45 KB
/
utils.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Author: Scito (https://scito.ch)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import csv
import json
import os
import shutil
from io import StringIO
import sys
import glob
# Ref. https://stackoverflow.com/a/16571630
class Capturing(list):
'''Capture stdout and stderr
Usage:
with Capturing() as output:
print("Output")
'''
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
del self._stringio # free up some memory
sys.stdout = self._stdout
def file_exits(file):
return os.path.isfile(file)
def remove_file(file):
if file_exits(file): os.remove(file)
def remove_files(glob_pattern):
for f in glob.glob(glob_pattern):
os.remove(f)
def remove_dir_with_files(dir):
if os.path.exists(dir): shutil.rmtree(dir)
def read_csv(filename):
"""Returns a list of lines."""
with open(filename, "r", encoding="utf-8", newline='') as infile:
lines = []
reader = csv.reader(infile)
for line in reader:
lines.append(line)
return lines
def read_csv_str(str):
"""Returns a list of lines."""
lines = []
reader = csv.reader(str.splitlines())
for line in reader:
lines.append(line)
return lines
def read_json(filename):
"""Returns a list or a dictionary."""
with open(filename, "r", encoding="utf-8") as infile:
return json.load(infile)
def read_json_str(str):
"""Returns a list or a dictionary."""
return json.loads(str)
def read_file_to_list(filename):
"""Returns a list of lines."""
with open(filename, "r", encoding="utf-8") as infile:
return infile.readlines()
def read_file_to_str(filename):
"""Returns a str."""
return "".join(read_file_to_list(filename))