1

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?

Blorgbeard
104k50 gold badges237 silver badges276 bronze badges
asked May 25, 2016 at 2:15

2 Answers 2

2

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
answered May 25, 2016 at 2:28
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered May 25, 2016 at 2:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.