You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python脚本进程终止/崩溃后自动重启及定时停止实现问询

Fixing Auto-Restart on Crash + Scheduled Stop for Your Python Script

Hey there! Let's work through your problem step by step. First, I noticed your original a.py has a few syntax issues that keep it from running—let's fix those first, then we'll build out the auto-restart and scheduled stop functionality you're after.


Step 1: Fix the Original a.py

Your script has two critical errors: missing a colon after def main(), and an uninitialized variable i. Here's the corrected version that runs as intended (outputs 1-10, one per second):

# a.py
import time

def main():
    i = 0  # Initialize loop variable to avoid NameError
    while i < 10:
        i += 1
        print(i)
        time.sleep(1)

if __name__ == '__main__':
    main()

Step 2: Add Auto-Restart on Crash

Your idea of importing the script as a module to monitor it is solid. We can build a simple monitor script that runs your main() function, catches any crashes, and restarts it automatically. I'll show you two approaches—pick the one that fits your use case.

Approach 1: Module Import + Exception Catching

This approach keeps everything in-process and is great for debugging:

# monitor.py
import a
import time

def monitor_script():
    # Set this to True if you want to restart even after normal exit
    restart_on_normal_exit = False

    while True:
        try:
            print("Starting a.py...")
            a.main()
            # If we reach here, the script exited normally
            if not restart_on_normal_exit:
                print("a.py exited normally—stopping monitor.")
                break
            print("a.py exited normally—restarting in 3 seconds...")
            time.sleep(3)
        except Exception as e:
            print(f"a.py crashed with error: {str(e)}—restarting in 3 seconds...")
            time.sleep(3)
        except KeyboardInterrupt:
            print("Manual interrupt detected—stopping monitor.")
            break

if __name__ == '__main__':
    monitor_script()

Approach 2: Independent Process Monitoring (with subprocess)

If you want full process isolation (good for scripts that might leak resources), use subprocess to launch a.py as a separate process:

# monitor.py
import subprocess
import time

def monitor_script():
    while True:
        print("Starting a.py as a separate process...")
        proc = subprocess.Popen(["python", "a.py"])
        proc.wait()  # Wait for the process to finish
        
        if proc.returncode == 0:
            print("a.py exited normally—stopping monitor.")
            break
        else:
            print(f"a.py crashed with exit code {proc.returncode}—restarting in 3 seconds...")
            time.sleep(3)
        except KeyboardInterrupt:
            print("Manual interrupt detected—killing a.py and stopping monitor.")
            proc.kill()
            break

if __name__ == '__main__':
    monitor_script()

Step 3: Add Scheduled Stop Functionality

Now let's add the ability to stop the monitor (and any running a.py instance) at a specific time or after a set duration.

Option 1: Stop After a Fixed Duration

This stops the entire monitor after a set number of seconds (e.g., 15 seconds):

# monitor.py (with duration-based stop)
import a
import time

def monitor_with_timeout(max_run_seconds=15):
    start_time = time.time()
    restart_on_normal_exit = False

    while True:
        # Check if we've exceeded the max run time
        if time.time() - start_time >= max_run_seconds:
            print("Max run time reached—stopping monitor.")
            break

        try:
            print("Starting a.py...")
            a.main()
            if not restart_on_normal_exit:
                print("a.py exited normally—stopping monitor.")
                break
            print("a.py exited normally—restarting in 3 seconds...")
            time.sleep(3)
        except Exception as e:
            print(f"a.py crashed with error: {str(e)}—restarting in 3 seconds...")
            time.sleep(3)
        except KeyboardInterrupt:
            print("Manual interrupt detected—stopping monitor.")
            break

if __name__ == '__main__':
    monitor_with_timeout(max_run_seconds=15)

Option 2: Stop at a Specific Time

This stops the monitor at a predefined time (e.g., 6:00 PM every day):

# monitor.py (with scheduled stop)
import a
import time
from datetime import datetime

def monitor_with_scheduled_stop(stop_hour=18, stop_minute=0):
    restart_on_normal_exit = False

    while True:
        # Check if current time matches the stop time
        now = datetime.now()
        if now.hour == stop_hour and now.minute == stop_minute:
            print("Scheduled stop time reached—stopping monitor.")
            break

        try:
            print("Starting a.py...")
            a.main()
            if not restart_on_normal_exit:
                print("a.py exited normally—stopping monitor.")
                break
            print("a.py exited normally—restarting in 3 seconds...")
            time.sleep(3)
        except Exception as e:
            print(f"a.py crashed with error: {str(e)}—restarting in 3 seconds...")
            time.sleep(3)
        except KeyboardInterrupt:
            print("Manual interrupt detected—stopping monitor.")
            break

if __name__ == '__main__':
    # Set to your desired stop time (24-hour format)
    monitor_with_scheduled_stop(stop_hour=18, stop_minute=0)

Quick Extra Tip

If you want a.py to check for the stop time itself (instead of relying on the monitor), you can add a time check inside its loop:

# Modified a.py with internal stop check
import time
from datetime import datetime

def main():
    i = 0
    stop_hour = 18
    stop_minute = 0

    while i < 10:
        now = datetime.now()
        if now.hour == stop_hour and now.minute == stop_minute:
            print("Scheduled stop time reached—exiting a.py.")
            break
        i += 1
        print(i)
        time.sleep(1)

if __name__ == '__main__':
    main()

内容的提问来源于stack exchange,提问作者user12742337

火山引擎 最新活动