作成
Pythonで文字列をプログラムとして実行
#### memo Pythonで文字列をプログラムとして実行する方法を紹介します。 ####title 1行の文字列をプログラムとして実行する場合。 ####source str = "print('hoge')" exec(str) ####ret hoge ####title 複数行の文字列をプログラムとして実行する場合。 ####source str = """ print('hoge1') print('hoge2') """ exec(str) ####ret hoge1 hoge2 ####title 外部ファイルを文字列として読み込み、プログラムとして実行する場合。 ####source (c:/test.txt 呼び出される外部プログラム) print('hoge3') print('hoge4') ####source (実行するプログラム) file = 'c:/test.txt' f = open(file, 'r', encoding='utf-8') str = f.read() f.close() exec(str) ####ret hoge3 hoge4 ####memo 以下のようなエラーがでた場合。は test.txt に BOMがついてる可能性がありますので、ファイル保存時に、#R*#UTF-8 の #R*#BOM無し で保存しましょう。 ####error File "
", line 1 SyntaxError: invalid character in identifier
wakatta 記法
投稿の仕方
基本的な記法
エンジニア向け記法
記法のサンプル
このコンテンツを見る