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_FILEstores 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:
- Open your user's crontab editor:
crontab -e - 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 withwhich python3if 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_FILEdirectory and the output/Downloadsfolder. - 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:
Add this at the start of yourimport 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)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
相关产品推荐
相关产品推荐

