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

如何使用Python在同一CMD窗口中随机运行文件夹内的.bat文件并循环执行Python脚本

Got it, let's sort this out for you! The issue with the solution you tried is that it spawns a new CMD window—we can fix that by tweaking how we run the .bat file and restart the script, all within the same terminal session.

Solution

Here's a complete Python script that does exactly what you need: picks a random .bat from your target folder, runs it in the same CMD window, then restarts itself once the .bat finishes.

Full Code

import os
import random
import subprocess
import sys

def get_random_bat_file(bat_directory):
    # Grab all .bat files from the specified folder (case-insensitive)
    bat_files = [
        filename 
        for filename in os.listdir(bat_directory) 
        if filename.lower().endswith(".bat")
    ]
    
    if not bat_files:
        print("Error: No .bat files found in the target folder!")
        sys.exit(1)
    
    # Return full path to a randomly selected .bat
    return os.path.join(bat_directory, random.choice(bat_files))

if __name__ == "__main__":
    # Replace this with your actual folder path (use raw string to avoid escape issues)
    TARGET_BAT_FOLDER = r"C:\Path\To\Your\Bat\Files"
    
    # Get our random .bat file
    selected_bat = get_random_bat_file(TARGET_BAT_FOLDER)
    print(f"Starting execution of: {selected_bat}\n")
    
    # Run the .bat file in the same CMD window, wait for it to finish
    try:
        # shell=True ensures the .bat is parsed correctly by Windows command shell
        subprocess.run(selected_bat, check=True, shell=True)
        print("\n.bat file executed successfully!")
    except subprocess.CalledProcessError as e:
        print(f"\nError running .bat file: {e}")
    
    # Restart the current Python script in the same window
    print("\nRestarting Python script now...")
    subprocess.run([sys.executable] + sys.argv)

Key Details Explained

  • Running the .bat in the same window: We use subprocess.run() without any creationflags (like CREATE_NEW_CONSOLE) that would spawn a new window. This ensures the .bat runs directly in the existing CMD session, and the script waits until it finishes before moving on.
  • Restarting the script: sys.executable gets the path to your current Python interpreter, and sys.argv captures all the original command-line arguments used to start the script. Combining these lets us restart the script exactly as it was launched.
  • Error handling: The try-except block catches any errors from the .bat file (like non-zero exit codes) so the script doesn't crash unexpectedly. You can modify this to skip restarting if the .bat fails, if that's what you want.

Quick Setup Tips

  1. Replace TARGET_BAT_FOLDER with the full path to your folder of .bat files. Use a raw string (prefix with r) to avoid issues with backslashes (e.g., r"C:\MyBats" instead of "C:\\MyBats").
  2. Make sure your Python script has permission to read the target folder and execute the .bat files.
  3. If you want to test without looping endlessly, you can add a condition to skip restarting (like a counter or a command-line flag).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:17:38