The Problem: Why Batch Files Fail
I recently encountered an unusual error when attempting to drop certain filenames into a Python app as inputs. After a moment, I realized the troubled ones had a comma in their filename, which should be totally valid, isn't it?
It turns out Windows Batch (cmd.exe) is built on legacy rules where the comma (,), semicolon (;), and equals sign (=) are treated as delimiters, exactly like a space.
When you drag a file named Data,Project.txt onto a .bat file:
Explorer sends the raw string to the command processor.
CMD sees the comma and splits the filename into two arguments:
%1becomes Data and%2becomesProject.txt.The comma is deleted from the stream entirely (🤦).
The Solutions: From Hack to Hero
| Method | The "Ugly Hack" (Batch) | The "Robust" Way (Shortcut) | The "Pro" Way (PyInstaller) |
| Setup | Create a .bat file with %* | Right-click .py > Create Shortcut | Compile script to a standalone .exe |
| The Trick | python script.py "%*" | Edit Target to: python.exe script.py | Drag-and-drop works natively |
| Pros | No extra files; easy to edit. | Immune to commas; supports fixed flags. | No Python install needed; very clean. |
| Cons | Fails if you drop multiple files. | Creates a .lnk file in your folder. | Needs re-compiling after code changes. |
Implementation Guide
1. The "FightPC" Batch Patch
If you absolutely must use a Batch file, use the "Catch-All" variable to force the pieces back together:
:: %* grabs the entire raw input, including commas and spaces set "RAW_INPUT=%*" python "%~dp0your_script.py" "%RAW_INPUT%" pause
Note: This works for one file with many commas, but it will merge multiple files into a single broken string.
2. The "Peace Treaty" (The Shortcut Method)
To stop fighting cmd.exe, bypass it.
Right-click your script -> Create Shortcut.
Properties -> Target:
python.exe "C:\Path\To\Script.py" --fixed-flagDrag your file onto this shortcut. Windows passes the path string directly to the Python process, preserving every single comma.
The Python "Shield"
Regardless of the method used, use this snippet in your Python code to ensure you're grabbing the right file from the argument list:
import sys
import os
def get_input_file():
# If using the Batch hack, join all args.
# If using a Shortcut, the file is usually sys.argv[-1].
path = " ".join(sys.argv[1:]).strip('" ')
if os.path.exists(path):
return path
else:
print(f"Critical Failure: Could not find path {path}")
return None
Comments