LoginSignup
5
7

More than 5 years have passed since last update.

Pythonで別のPythonファイルを作って実行結果を得る

Posted at

変数の書き換えでどうにもならないときに使った方法である.
具体的には,Sympyで立てた計算式をSciPyで計算したいときに使った(もしかしたら別記事に書くかもしれない).

環境

  • Python 3.6.1

コード

外部ファイルに1+1の計算をするコードを書き,その結果を得て出力するプログラムである.

import subprocess

def main():
    content = "def main():\n    print(1+1)\n\nif __name__=='__main__':\n  main()" # 外部ファイルの内容
    f = open("./tmp.py","w") # 今いるディレクトリのtmp.pyを開く (存在しなければ作成される)
    f.write(content) # contentをtmp.pyに書き込む
    f.close()
    # tmp.pyを実行する
    try:
        res = subprocess.check_output(["python tmp.py"],shell=True)
        res = res.decode("utf-8") # resはバイナリ形式なのでデコードする
        print(res) # ここでは2を得る
    except:
        print("エラー")

if __name__ == "__main__":
    main()

subprocessを用いて指定したコマンド(python tmp.py)を実行する.
結果のresは<class 'bytes'>なので,デコードして使いたい形式に変換する必要がある.
ここでのデコードした後のresは<class 'str'>である.

作成されたtmp.pyは以下のようになる.

tmp.py
def main():
    print(1+1)

if __name__=='__main__'
  main()
5
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7