How to run another program by python?

Asked

Viewed 6,777 times

7

I’m looking to make a calculation engine on Python. For example, I have a name program engine.py, that takes an equation and returns the roots. I wanted to write another program named interface.py, that would just take the equation and send it to the engine to calculate and take the returned value. You can do this?

engine py.

x = str(input())  
x = x.replace("-","+-")  
Eq = list(x.split("+"))  
b = 0  
c = 0  
if "" in Eq: Eq.remove("")  
for i in range(0,len(Eq)):
    if (Eq[i] == "x²"):    
        a = 1  
    elif (Eq[i] == "-x²"):  
        a = -1  
    elif "x²" in Eq[i]:  
        aux = Eq[i]  
        a = int(aux.replace("x²",""))  
    elif (Eq[i] == "x"):  
        b = 1  
    elif (Eq[i] == "-x"):  
        b = -1  
    elif "x" in Eq[i]:
        aux = Eq[i]
        b = int(aux.replace("x",""))
    else:
        c = int(Eq[i])
delta = (b * b) - 4 * a * c 
print("Delta:",delta)
if delta<0:
    print('Essa equacao nao tem raiz real')
elif delta==0:
    x1 = (-b)/(2*a)
    print('Raiz:',x1)
else:
    from math import sqrt
    x1 = (-b+sqrt(delta))/(2*a)
    x2 = (-b-sqrt(delta))/(2*a)
    print('Raizes:')
    print("x':",x1)
    print("x'':",x2)  

Interface.py.

x = input()  
y = manda_para_engine(x)
print(x)

something like that

  • What have you done? click [Edit] and add your code.

1 answer

8


Yes.

Define your file engine.py more or less as follows:

def calcular_equacao(a, b, c):
    delta = (b * b) - 4 * a * c 
    print("Delta:", delta)
    if delta<0:
        print('Essa equacao nao tem raiz real')
        return None
    elif delta==0:
        x1 = (-b)/(2*a)
        return x1
    else:
        from math import sqrt
        x1 = (-b+sqrt(delta))/(2*a)
        x2 = (-b-sqrt(delta))/(2*a)
        return (x1, x2)  

In the archive interface.py, import engine.py as follows:

import engine

To call the engine function:

a = engine.calcular_equacao(1, 2, 3)

engine.py and interface.py must be in the same directory. Making a print of a, the result must be the tuple with the roots, or an integer, or None if it has no real roots.

Note that I have not directed the treatment logic of the expression to the function. The function is simply called with a, b and c already completed.

  • he made an error in import engine: in the module named 'engine'

  • 1

    You saved the file engine.py in the same directory that called Python?

  • yes, both are in the same directory, I will put the two alone in the same directory

  • Now it worked man, thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.