Python 如何在主脚本中运行另一个脚本

Python 如何在主脚本中运行另一个脚本,python,Python,我不知道如何在我的主Python脚本中运行另一个脚本。例如: 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")) 如何在不必在索引脚本中编写计算器代码的情况下在此脚本中运行计算器脚本?您需

我不知道如何在我的主Python脚本中运行另一个脚本。例如:

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"))

如何在不必在索引脚本中编写计算器代码的情况下在此脚本中运行计算器脚本?

您需要使用execfile,sintax可在以下位置获得:。例如:

execfile("calculator.py")
如果您使用的是Python 3.x,请使用以下代码:

with open('calculator.py') as calcFile:
    exec(calcFile.read())

PS:您应该考虑使用导入语句,因为更简单和有用的是

,因为您的另一个“脚本”是一个Python模块(.pyfile),您可以导入要运行的函数:

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"))
计算器.py

def multiply(a, b)
    return a * b