Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.0 kB
0
Indexable
Never
import os

class Calculator:

    operations = ['+', '-', '*', '/', '.']

    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        return a / b

    def get_expression(self):
        user_input = input("Input the expression: op n1 n2 ")
        return bytes(user_input, encoding="UTF-8")

    def find_result(self, user_input):
        user_input = user_input.decode("utf-8").split()
        operand = user_input[0]
        a = int(user_input[1])
        b = int(user_input[2])
        if operand == '+':
            return str(my_cl.add(a, b)).encode("utf-8")
        elif (operand == '-'):
            return str(my_cl.subtract(a, b)).encode("utf-8")
        elif (operand == '*'):
            return str(my_cl.multiply(a, b)).encode("utf-8")
        elif (operand == '/'):
            return str(my_cl.divide(a, b)).encode("utf-8")
        else:
            print("ERROR")


def check_quit(user_input):
    tmp = user_input.split()
    print(tmp)
    if tmp[0] == '.':
        return 1
    else:
        return 0


r2, w2 = os.pipe()
r1, w1 = os.pipe()

pid = os.fork()

if pid > 0:
    os.close(r2)
    os.close(w1)
else:
    my_cl = Calculator()
    os.close(w2)
    os.close(r1)

while (1):
    if pid > 0:
        user_input = input("Input the expression: op n1 n2 ")
        if not check_quit(user_input):
            os.write(w2, bytes(user_input, encoding="UTF-8"))
            print("Result:", os.read(r1, 100).decode("utf-8"))
        else:
            print("See you later!")
            os.close(w2)
            break

    else:
        user_input = os.read(r2, 100)
        if user_input:
            try:
                os.write(w1, my_cl.find_result(user_input))
            except ZeroDivisionError:
                os.write(w1, b"Zero devision!")
                continue
        else:
            os.close(r2)
            break