LoginSignup
29
32

More than 3 years have passed since last update.

pythonファイルをスクリプト実行

Last updated at Posted at 2016-06-09

pythonファイルをスクリプト実行

MATLABでの.mファイルのようにpythonファイルのスクリプト実行をしたいと思い調べてみた

%run -i (IPython 環境の場合)

条件:IPython(Jupyter Notebookなど)

「test.py」のあるフォルダで

%run -i test.py

によって、「test.py」のスクリプトでの実行ができる。

名前空間はメインのものと同じとなるもよう。
forの中に入れることも可能。

execコマンド (IPython以外でも使える方法) 2018.9.7追記

「test.py」のあるフォルダで

with open('test.py', 'r', encoding='utf-8') as f:
    script = f.read()#スクリプトのファイルを文字列として読み込む
    exec(script) #execで文字列を実行

によって、「test.py」のスクリプトでの実行ができる

通常、別ファイルからモジュールとしてをimportを使った場合、グローバル変数がファイル毎に異なるので、純粋なスクリプトにはならない模様。
名前空間が別ファイルにまたがり、可読性が悪化するなど、あくまで個人の実験用として使うべき。

29
32
0

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
29
32