-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
84 lines (60 loc) · 2.17 KB
/
main.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
import logging
import os
import sys
from datetime import datetime
from libs.Finder import Finder
from libs.ArgumentParser import ThrowingArgumentParser, ArgumentParserError
OUTPUT_FOLDER = "output"
def createLogger(loggerName: str):
if not os.path.exists("logs"):
os.mkdir("logs")
logger = logging.getLogger(loggerName)
logger.setLevel(logging.INFO)
fileHandler = logging.FileHandler("logs/report.log")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - line %(lineno)d: %(message)s')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
return logger
def getOutputFilePath() -> str:
if not os.path.exists(OUTPUT_FOLDER):
os.mkdir(OUTPUT_FOLDER)
outputFileName = "output_{}.txt".format(datetime.timestamp(datetime.utcnow()))
return os.path.join(OUTPUT_FOLDER, outputFileName)
def main():
logger = createLogger(__name__)
logger.info('script started')
argp = ThrowingArgumentParser()
argp.add_argument("file", type = str)
argp.add_argument("-r", "--regexp", type = str)
try:
arguments = argp.parse_args()
except ArgumentParserError as e:
logger.error(e)
sys.exit(e)
logger.info("got arguments: {}".format(arguments))
finder = Finder(arguments.regexp)
if not os.path.isfile(arguments.file):
message = "\"{}\" is not a file".format(arguments.file)
logger.error(message)
sys.exit(message)
try:
with open(arguments.file, encoding="utf8") as fileData:
data = fileData.read().split("\n")
except IOError as e:
logger.error(e)
sys.exit(e)
try:
processedData = finder.processData(data)
except Exception as e:
logger.error(e)
sys.exit(e)
logger.info("data processed")
processedDataWithNewLines = [it + "\n" for it in processedData]
outputFilePath = getOutputFilePath()
with open(outputFilePath, mode="w", encoding="utf8") as outputFile:
outputFile.writelines(processedDataWithNewLines)
message = "success: saved to {}".format(outputFilePath)
logger.info(message)
print(message)
if __name__ == "__main__":
main()