简体   繁体   中英

How do I run another script, inside my main script

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM