-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculate
executable file
·90 lines (73 loc) · 2.22 KB
/
calculate
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
#!/usr/bin/env python3
# built-in imports
import argparse
import logging
# custom imports
import calculator
import calculator_ui
import client
LOG = logging.getLogger(__name__)
LOG_FILE = "calculator_log.txt"
LOG_FORMAT = "%(filename)-18s:%(lineno)-8d %(levelname)-8s - %(message)s"
def create_logger(log_file: str) -> None:
"""Creates logger for console and text file."""
logging.basicConfig(
filename=log_file,
level=logging.DEBUG,
format=f"[%(asctime)s] {LOG_FORMAT}",
datefmt="%H:%M:%S",
)
root_logger = logging.getLogger("")
root_logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(LOG_FORMAT)
console = logging.StreamHandler()
console.setFormatter(formatter)
root_logger.addHandler(console)
def parse_args() -> argparse.Namespace:
"""Parses command-line args to handle calculator execution."""
parser = argparse.ArgumentParser(
prog="Calculator",
description="Simple Python calculator.",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
"--input",
"-i",
type=str,
required=False,
help="Arithmetic equation to solve.",
)
parser.add_argument(
"-ip",
nargs="?",
const="0.0.0.0",
type=str,
help="IP address to connect.\nIf only flag used, defaults to '0.0.0.0'.",
)
args = parser.parse_args()
return args
def run_client(ip: str) -> str:
"""Initializes and connects client to server."""
message = input("-> ")
client_inst = client.Client(ip=ip)
connected = client_inst.connect_to_host()
if not connected:
return False
result = client_inst.send_to_server(message)
return result
def main():
"""Launch the tool."""
create_logger(LOG_FILE)
args = parse_args()
if args.input:
LOG.info("- - - - - Calculator CLI - Built-In - - - - -")
calc = calculator.Calculator()
return calc.run(args.input)
elif args.ip:
LOG.info("- - - - - Calculator CLI - Server - - - - -")
return run_client(args.ip)
else:
LOG.info("- - - - - Calculator Application - - - - -")
calculator_ui.main()
if __name__ == "__main__":
main()