LoginSignup
0
0

More than 1 year has passed since last update.

[Python]スクリプトで自分自身を呼び出す

Posted at

はじめに

例えば,sample.py の中で sample.py を呼び出します.
同じファイルを複数起動させたい時などに使えます.

コード

file = open(__file__, encoding='UTF-8') # 自分自身のファイルをUTF-8で読み込む
exec(file.read()) # ファイルを実行する

実行中のスクリプトのパスを__file__で取得できます.
exec()関数はPythonのコードオブジェクトを実行する組み込み関数です.

記述例

ここでは,実際に Tkinter (GUIを扱うライブラリ) を用いて「ボタンを押すと複製する」というようなスクリプトを作ってみます.

import tkinter as tk

# 新規ウィンドウを開く
def new_window():
    file = open(__file__, encoding='UTF-8')
    exec(file.read())

# ウィンドウの設定
disp = tk.Tk()
disp.title('sample')
disp.geometry('400x300')

#ボタンの設定
fonts = (', 50')
button = tk.Button(disp, text='複製', height=20, width=20, command=new_window, font=fonts, bg='#ffc0cb')
button.pack(fill = 'both', padx=50, pady=100)

disp.mainloop()

上記のコードで,ボタンを押すだけで無限にウィンドウを増殖させるスクリプトができます(下図).
image.png
それぞれのウィンドウは独立しているので,元のウィンドウを消しても複製させたウィンドウは残り,正常に動きます.

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