Repository navigation
Expand file tree
/
Copy pathprefixcalc.py
More file actions
executable file
·110 lines (77 loc) · 1.91 KB
/
Copy pathprefixcalc.py
File metadata and controls
executable file
·110 lines (77 loc) · 1.91 KB
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
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env python3
""" Calculadora prefix.
Funcionamento:
Argumentos: [operação] [n1] [n2]
Operações:
sum -> +
sub -> -
mul -> *
div -> /
Uso:
#Operação padrão:
$ prefixcalc.py
operação: sum
n1: 5
n2: 4
9.0
$ prefixcalc.py sum 5 2
7.0
$ prefixcalc.py mul 10 5
50.0
$ prefixcalc.py div 3
Invalid operation
Os resultados serão salvos em `prefixcalc.log`
ex:
timestamp - username - sum 2 4 = 6
timestamp - username - sub 5 4 = 1
"""
__version__ = "0.2.0"
__author__ = "Marcelo Garcia"
__license__ = "unlicense"
import sys
import os
from datetime import datetime
user = os.getenv("USER", "anonymous")
arguments = sys.argv[1:]
valid_arguments = ("sum", "sub", "mul", "div")
if not arguments:
operation = input("operação: ").strip()
if operation not in valid_arguments:
print("Invalid arguments: invalid operation")
sys.exit()
n1 = input("n1: ")
n2 = input("n2: ")
arguments = [operation, n1, n2]
elif len(arguments) != 3:
print("Invalid arguments: expected three arguments")
sys.exit()
elif arguments[0] not in valid_arguments:
print("Invalid arguments: invalid operation")
sys.exit()
operation, *nums = arguments
validated_numbers = []
for num in nums:
if not num.replace(".", "").isdigit(): #valida se a string só tem digitos
print("Invalid arguments: arguments 2 and 3 must be numbers")
sys.exit()
elif "." in num:
num = float(num)
else:
num = int(num)
validated_numbers.append(num)
n1, n2 = validated_numbers
operations = {
"sum": n1 + n2,
"sub": n1 - n2,
"mul": n1 * n2,
"div": n1 / n2, #TO DO: tratar ZeroDivisionError
}
result = operations[operation]
current_time = datetime.now()
time_stamp = current_time.timestamp()
date_time = datetime.fromtimestamp(time_stamp)
log = f"{date_time} - {user} - {operation} {n1} {n2} = {result}"
filepath = os.path.join(os.curdir, "prefixcalc.log")
with open(filepath, "a") as file:
file.write(f"{log}\n")
print(f"O resultado é {result}")