LoginSignup
0
0

More than 1 year has passed since last update.

exec関数を使って、ファイル読込で取得したPythonコードの文字列を実行

Posted at

個人的なメモ 別ファイルの処理を呼ぶ際は通常、import文を使いますが、 exec関数を使って、擬似的に値のやり取りをする方法を書きます。

やりたいこと

1.exec関数を使う前に別ファイルで使う変数を擬似的に宣言
2.exec関数を通して変数を授受し、グローバル変数の如く扱う
3.結果を表示

ソースコード

Pythonから読み込むテキストファイル

input.txt
dictionary["key1"]="value1"
dictionary["key2"]="value2"
dictionary["key3"]="value3"
dictionary["key4"]="value4"
dictionary["key5"]="value5"

Pythonソースコード

execution.py
from os.path import dirname
with open(dirname(__file__) + '/input.txt') as f:
    variable_name = 'dictionary'
    # テキストファイル内の変数と同名のキーを持つ連想配列を作成
    result = {variable_name: {}}
    # exec関数の利用
    # 第1引数: テキストファイルの全文を指定
    # 第2引数: 作成した連想配列を指定
    # 第3引数: 指定した場合、第2引数よりも優先して処理される
    exec(f.read(), result)
    # テキストファイルに書かれたキーと値を持つ連想配列を表示
    # {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5'}
    print(result[variable_name])
    dictionary = result[variable_name]
    # 値を表示
    # value1
    print(dictionary['key1'])

まとめ

exec関数を使うと別ファイルに書かれている処理を実行した後、
そのまま使い続けることができる。

0
0
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
0
0