pythonで自動的にスクリプトファイルを実行しようと。scheduleモジュールを使用してできることが分かり実装しようとしたら、あれ?みたいな。
ほかファイルを実行させるにはimportで実行・・・と書いたら、最初の1回だけ実行されて、繰り返し実行されない。
あれえ?なんでぇ?
当たり前だよね。わかれば簡単、初心者の思い込みから間違いでした。
importされた時点でそのファイルは実行されるが、一度importされたものは2回目は実施されないので…という当たり前のルールから。
アホやん!
ということで、from ファイル名 import 関数名で、組み込みが正しい。というか、これが常識なのね。あぁ、当たり前って初心者にはつらい。
# =================================== # import # =================================== import time import datetime import schedule # =================================== # function # =================================== # Do Job for a certain period of time def job(): StartMessage(timestamp()) time.sleep(5) # ============================== # End message # ============================== EndMessage(timestamp()) # =================================== # function(sub) # =================================== def timestamp(): dt1 = datetime.datetime.now() dt2 = dt1.strftime('%Y_%m/%d_%H:%M_%S') return dt2 def ScheduleStartMessage(timestamp): print(timestamp,"===Schedule started===") def StartMessage(timestamp): print(timestamp,"===Process started===") def EndMessage(timestamp): print(timestamp,"===Process done===") # =================================== # execution # =================================== def main(): # Do Job for a certain period of time schedule.every(10).seconds.do(job) ScheduleStartMessage(timestamp()) # Checking schedule run while True: schedule.run_pending() time.sleep(1) if __name__ == "__main__": main()
◆実行結果
2021_04/28_10:59_19 ===Schedule started=== 2021_04/28_10:59_29 ===Process started=== 2021_04/28_10:59_34 ===Process done=== 2021_04/28_10:59_44 ===Process started=== 2021_04/28_10:59_49 ===Process done=== 2021_04/28_10:59_59 ===Process started=== 2021_04/28_11:00_04 ===Process done=== 2021_04/28_11:00_14 ===Process started=== 2021_04/28_11:00_19 ===Process done=== 2021_04/28_11:00_29 ===Process started=== 2021_04/28_11:00_34 ===Process done=== 2021_04/28_11:00_44 ===Process started=== 2021_04/28_11:00_49 ===Process done=== 2021_04/28_11:00_59 ===Process started=== 2021_04/28_11:01_04 ===Process done===
複数のファイルを読み込んで…そっか、今更ながらCのincludeを思い出した。そうだそうだ、最初にファイルを読み込んで、そのうえで関数を呼び出すんだっけ。仕事で取り扱ったスクリプトは既にひな型が出来上がっていて、作業者はデータ打ちに徹していただけだからなぁ。いろんなファイル読み込んで関数の嵐になると、データ打ちしている人には中身なんて理解しようもないし。
とりあえずscheduleのひな型を作成してみた。無事に動いたので、次はほかファイルの関数を読み込んで、複数のファイルを実行しようと思う。