2016-05-25 4 views
1

メインの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")) 

は、どのように私は、インデックススクリプトの内部で計算コードを記述することなく、本の内部の私の電卓スクリプトを実行しますか?

答えて

1

execfileを使用する必要があり、sintaxはhttps://docs.python.org/2/library/functions.html#execfileで利用できます。例:

execfile("calculator.py") 

あなたが使用している場合は、このfolowingコードを使用して、Pythonの3.xのです:

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

PS:あなたは

2

よりシンプルかつ有用であるので、import文を使用して検討すべきですあなたの他の "スクリプト"は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 
関連する問題