Reputation: 15
I don't know how to run another script inside my main Python script. For example:
Index.py:
Category = "math"
Print (Category)
Print ("You can use a calculator")
Print ("What is 43.5 * 7")
#run calculator.py
Answer = int(input("What is your answer"))
How do I run my calculator script inside of this without having to write the calculator code inside of my index script?
Upvotes: 1
Views: 97
Reputation:
You need to use execfile, and the sintax are available on: https://docs.python.org/2/library/functions.html#execfile. Example:
execfile("calculator.py")
If you using are Python 3.x, Use this folowing code:
with open('calculator.py') as calcFile:
exec(calcFile.read())
PS: You should consider use the import statement, because is more simple and useful
Upvotes: 1
Reputation: 5276
Since your other "script" is a python module (.py file) you can import the function you want to run:
index.py:
from calculator import multiply # Import multiply function from calculator.py
category = "math"
print(category)
print("You can use a calculator")
print("What is 43.5 * 7")
#run calculator.py
real_answer = multiply(43.5, 7)
answer = int(input("What is your answer"))
calculator.py
def multiply(a, b)
return a * b
Upvotes: 2