如何用Python实现将.txt文件拖入.exe程序运行的功能?
Hey there! I've run into this exact scenario before when automating GUI tools that only seem to accept file drag-and-drop—let's break down how to solve this, starting with the easiest (and most reliable) method first.
方法1:利用命令行参数(优先推荐)
Most converter EXEs actually treat drag-and-drop actions as passing the file path as a command-line argument. Before writing any code, test this manually:
Open Command Prompt, type
"<path-to-your-converter.exe>" "<path-to-a-test.txt>", and hit enter. If the converter runs and processes the file, this method will work perfectly.
Here's the Python code to automate this, including a file picker (you can adapt the file selection part to your existing code):
import subprocess import tkinter as tk from tkinter import filedialog # Hide the Tkinter root window (we just need the file picker) root = tk.Tk() root.withdraw() # Let user select a TXT file selected_txt = filedialog.askopenfilename( title="Select TXT File to Convert", filetypes=[("Text Files", "*.txt")] ) if selected_txt: # Replace this with the full path to your converter EXE converter_path = r"C:\Tools\MyConverter.exe" try: # Run the converter with the TXT file as an argument subprocess.run( [converter_path, selected_txt], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) print("Conversion completed successfully!") except subprocess.CalledProcessError as e: print(f"Error during conversion: {e.stderr}") except FileNotFoundError: print(f"Couldn't find the converter at: {converter_path}")
为什么这个方法最好?
- It's simple, reliable, and doesn't depend on finicky GUI window tricks.
- Handles spaces in file paths automatically (subprocess takes care of quoting behind the scenes).
- You can capture output/errors from the converter for easy debugging.
方法2:模拟GUI拖放(仅当方法1失效时使用)
If your converter doesn't support command-line arguments (rare, but possible), you'll need to simulate the actual drag-and-drop using Windows API calls. We'll use the pywin32 library for this.
First, install the library:
pip install pywin32
Then use this code:
import win32api import win32con import win32gui import win32ui import tkinter as tk from tkinter import filedialog import os import time def simulate_drag_drop(window_handle, file_path): # Prepare the file path (absolute path is required) abs_file_path = os.path.abspath(file_path) # Create a data object for the file data_object = win32ui.CreateFileDataObject([abs_file_path]) # Send the WM_DROPFILES message to the window win32gui.SendMessage( window_handle, win32con.WM_DROPFILES, data_object.GetHandle(), 0 ) # Select the TXT file root = tk.Tk() root.withdraw() selected_txt = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")]) if selected_txt: converter_path = r"C:\Tools\MyConverter.exe" try: # Launch the converter EXE win32api.ShellExecute(0, "open", converter_path, "", "", 1) # Wait for the window to load (adjust the sleep time if needed) time.sleep(2) # Find the converter window by its title (replace with your window's actual title) converter_window = win32gui.FindWindow(None, "My Converter Tool") if converter_window: # Enable drag-and-drop acceptance for the window win32gui.SendMessage( converter_window, win32con.WM_DROPFILES, 0, win32con.DROPEFFECT_COPY ) # Simulate the drag-and-drop simulate_drag_drop(converter_window, selected_txt) print("Drag-and-drop simulated successfully!") else: print("Couldn't find the converter window—double-check the window title.") except Exception as e: print(f"Error during simulation: {str(e)}")
注意事项:
- You need to know the exact window title of your converter (use tools like Window Spy from AutoHotkey to find it).
- The sleep time might need adjustment if your converter takes longer to launch.
- This only works on Windows (since it uses Win32 APIs).
快速测试步骤
- First verify if method 1 works (command-line test).
- If method 1 fails, proceed to method 2 and tweak the window title/sleep time as needed.
内容的提问来源于stack exchange,提问作者Jbu

