繁体   English   中英

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

[英]How do I run another script, inside my main script

我不知道如何在我的主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模块(.py文件),您可以导入要运行的函数:

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

您需要使用execfile,并且可以在以下网址获得sintax: https//docs.python.org/2/library/functions.html#execfile 例:

execfile("calculator.py")

如果您使用的是Python 3.x,请使用以下代码:

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

PS:你应该考虑使用import语句,因为它更简单实用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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