You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何定时终止程序并重启,延续循环变量i的执行?

Got it, let's solve this step by step. The core issue here is tracking your loop's progress across restarts and ensuring the script exits after 10 minutes. Here's a practical, reliable approach:

Step 1: Modify Your Python Script to Track Progress & Enforce Timeouts

We'll use a simple text file to save the last processed i value, and add a check to exit the script once it's run for 10 minutes. Here's the updated code:

import time
import os

# Configuration - adjust these paths to match your setup
STATE_FILE = "/home/your_username/last_i.txt"  # Save progress here
MAX_RUN_MINUTES = 10
TARGET_TOTAL = 4954  # Your original range upper limit
OUTPUT_PATH = "/Downloads/pos_{}.h5"

def get_starting_i():
    """Load the last processed index, or start at 0 if no state exists."""
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r") as f:
            try:
                return int(f.read().strip())
            except ValueError:
                # Handle invalid file content gracefully
                return 0
    return 0

def save_progress(i):
    """Save the next index to process (since current i is done)."""
    with open(STATE_FILE, "w") as f:
        f.write(str(i))

def main():
    start_time = time.time()
    current_i = get_starting_i()
    
    # Exit early if we've already finished all tasks
    if current_i >= TARGET_TOTAL:
        print("All tasks completed!")
        if os.path.exists(STATE_FILE):
            os.remove(STATE_FILE)
        return
    
    for i in range(current_i, TARGET_TOTAL):
        # Insert your existing processing code here
        # ........
        # Save your file using the formatted path
        save(OUTPUT_PATH.format(i))
        
        # Check if we've exceeded the 10-minute runtime
        elapsed = time.time() - start_time
        if elapsed >= MAX_RUN_MINUTES * 60:
            save_progress(i + 1)
            print(f"Runtime limit reached. Saved progress: next run starts at {i+1}")
            return
    
    # If we finish all tasks, clean up the state file
    save_progress(TARGET_TOTAL)
    print("All tasks completed successfully!")
    if os.path.exists(STATE_FILE):
        os.remove(STATE_FILE)

if __name__ == "__main__":
    main()

Key Details in This Script:

  • Progress Tracking: The STATE_FILE stores the next index to process, so even if the script is killed, it picks up right where it left off.
  • Timeout Enforcement: We check the elapsed time on every loop iteration (you could optimize this to check every N iterations if needed, but for simplicity, per-loop works).
  • Cleanup: Once all 4954 tasks are done, the state file is deleted to avoid unnecessary checks.
Step 2: Set Up Cron to Restart the Script

Now we'll use cron to launch the script every 10 minutes (or whenever it exits). Here's how:

  1. Open your user's crontab editor:
    crontab -e
    
  2. Add this line to schedule the script (replace paths with your actual setup):
    */10 * * * * /usr/bin/python3 /path/to/your/script.py >> /home/your_username/script_logs.log 2>&1
    

What This Cron Line Does:

  • */10 * * * *: Runs the command every 10 minutes, every hour, every day, etc.
  • /usr/bin/python3: Path to your Python 3 executable (verify with which python3 if unsure).
  • /path/to/your/script.py: Full path to your modified Python script.
  • >> /home/your_username/script_logs.log 2>&1: Logs all output (and errors) to a file, so you can debug if something goes wrong.
Extra Tips for Reliability
  • File Permissions: Make sure your user has read/write access to the STATE_FILE directory and the output /Downloads folder.
  • Prevent Duplicate Runs: To avoid multiple instances of the script running at once (if one takes longer than 10 minutes), add a file lock. Here's a quick way to implement it:
    import fcntl
    
    LOCK_FILE = "/home/your_username/script_lock.lock"
    lock = open(LOCK_FILE, "w")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        print("Another instance is already running. Exiting.")
        exit(1)
    
    Add this at the start of your main() function.
  • Test First: Temporarily set MAX_RUN_MINUTES = 0.5 (30 seconds) to test the progress saving and restart logic without waiting 10 minutes.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:01:17