簡體   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