如何使用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 anycreationflags(likeCREATE_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.executablegets the path to your current Python interpreter, andsys.argvcaptures 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-exceptblock 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
- Replace
TARGET_BAT_FOLDERwith the full path to your folder of .bat files. Use a raw string (prefix withr) to avoid issues with backslashes (e.g.,r"C:\MyBats"instead of"C:\\MyBats"). - Make sure your Python script has permission to read the target folder and execute the .bat files.
- 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
相关产品推荐
相关产品推荐

