Pythonプログラムをダブルクリックで実行したい
前回までにダブルクリックで実行できるPythonプログラムを作成してきました。

ということで最終工程。
実際にダブルクリックして実行してみようというのが今回の記事。
前回までに「数値データが入っているCSVファイルを読み込み、なんか計算をして、グラフにして書き出して、同時にCSVファイルを書き出す」というプログラムが完成して、フォルダ構造はこんな感じになっているかと思います。

この中で「test_out.csv」と「out_fig.png」は出力されたファイルで、これから再度実行してこれらのファイルが生成されるのでとりあえず削除しておきましょう。
ちなみに「testdata.csv」はこれから読み込む数値データのファイル。
「test_program.ipynb」がAnaconda用のPythonプログラム。
そして「test_program.py」が今回実行したいファイルです。
「test_out.csv」と「out_fig.png」を削除して、フォルダ構造はこうなっていると思います。

ということでお待ちかね。
「test_program.py」をダブルクリックしてみましょう。
ダブルクリックした結果:失敗編
ダブルクリックしたら、こんな二つのウインドウが開きました。


単純に「Python」がターミナルで起動し、それと同時に「IDLE」というPythonのエディタソフトが開いただけになってしまいました。
Python Launcher.app
実はPythonを実行するには「.py」ファイルをダブルクリックした際に使用するソフトをPythonエディタソフトである「IDLE」から、Python実行ソフトである「Python Launcher.app」にする必要があるのです。
とりあえず今回作成したPythonプログラムを「Python Launcher.app」で実行してみて、ちゃんと目的通りの結果が得られるか試してみましょう。
ということで「test_program.py」を右クリックします。

出てきたメニューのうち、「このアプリケーションで開く」をクリック。

「Python Launcher.app」をクリックします。

するとターミナルが起動し、少し待つと「[プロセスが完了しました]」と表示されます。

これでPythonプログラムを実行したフォルダを確認してみます。
すると「test_out.csv」、「out_fig.png」が作成されています。

もちろん中身も意図した通りになっています。


また再度実行しますので、「test_out.csv」と「out_fig.png」は削除しておきましょう。
ダブルクリックで実行できるよう設定
「Python Launcher.app」で実行できることが分かったので、ダブルクリックで実行できるようMacの設定をしていきましょう。
先ほど同様「test_program.py」を右クリックします。

今度は「情報を見る」をクリックします。

「このアプリケーションで開く:」の下のプルダウンメニューをクリックします。

「Python Launcher.app」をクリック。

すると「このアプリケーションで開く」のプルダウンメニューが「Python Launcher.app」に変わります。
ただこのままではこのファイルのみが「Python Launcher.app」で開かれます。
「.py」の拡張子のものは全て「Python Launcher.app」で開くようにしたいので、「すべてを変更…」をクリックします。

確認ウインドウが現れるので、「続ける」をクリック。

すると「このアプリケーションで開く」のプルダウンメニューが「Python Launcher.app(デフォルト)」となります。

(デフォルト)となることで、「.py」という拡張子がつくファイルは全て「Python Launcher.app」で開かれます。
これで「test_program.py」をダブルクリックすると、ターミナルが自動で起動し、処理が行われます。

[プロセスが完了しました]と表示されると、「test_out.csv」と「out_fig.png」が作成されました。

これで目的だったダブルクリックでPythonプログラムを実行できるようになりました。
Pythonプログラム側、そしてMac側と両方を調整する必要がありましたが、これでPythonが使用できる場面がさらに広がりますので、普段は使わないにしても頭の片隅に入れておいて損はないかなと思います。
次回はもう一つの実行方法、ターミナルからPythonプログラムを実行してみたいと思います。

ということで今回はこんな感じで。
2022年4月28日追記)
上記の設定をした後、Pythonプログラムをダブルクリックしても実行されない(開くアニメーションはでるが実行されない)場合は、一つターミナルを開いてから、Pythonプログラムをダブルクリックしてみてください。
コメント