LoginSignup
1
1

無限リピートサンプル

Posted at

趣旨

既に提供されてるPythonプログラムを中身を書き換えずに終了と同時に再起動して無限リピートしたいという欲望が原動力になって書くことにした記事です。

subprocessを利用します。全体の概要・詳細を知りたい方は以下のURLから公式ドキュメントが確認できます。

公式ドキュメントが難しいという方は@virusyunさんの「Pythonのsubprocessについて」という記事がもう少しわかりやすいかなと思います。

以下のLNMarkets提供の自動売買botに利用できる無限リピート用のサンプルコードです。少しアレンジして書き換える必要があります。

import subprocess

def monitor_and_restart(script_path, end_line):
    while True: 
        with subprocess.Popen(['python', script_path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as proc:
            print(f"Monitoring script: {script_path}")
            for line in proc.stdout:
                print(line, end='')
                if end_line in line:
                    print(f"Detected end line: {line}")
                    break
        print("Restarting script...")

script_path = "/home/user/main.py"
end_line = "Sample"

monitor_and_restart(script_path, end_line)

借りてるサーバーのうち1つがあまりにも低スペックすぎてPandasを導入しようとするとKillされたのでいじけて制限強めの方の少しだけ高スペックのサーバーで導入することにしました。お金毎月払ってるのに稼働できないのくやしいので Mini PC 買って自宅サーバーから運用したく思います。

1
1
2

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