python
path_handling
ai_generated
true
FileNotFoundError: No such file or directory — subprocess fails on path with spaces
ID: python/subprocess-space-in-path-split
92%Fix Rate
93%Confidence
4Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
subprocess.run() with shell=False splits path containing spaces into multiple arguments instead of treating it as one path.
genericWorkarounds
-
95% success Pass command as a list of separate arguments, not a single string
subprocess.run(['ls', '/path/with spaces/file.txt']) # list form, not string
Sources: https://docs.python.org/3/library/subprocess.html#subprocess.run
-
88% success If shell=True is needed, use shlex.quote() to properly escape paths
import shlex; subprocess.run(f'cat {shlex.quote(path)}', shell=True)Sources: https://docs.python.org/3/library/shlex.html#shlex.quote
Dead Ends
Common approaches that don't work:
-
Use os.system() instead of subprocess
90% fail
os.system() is less secure (shell injection) and has the same quoting issues
-
Add backslash escapes to the path string
85% fail
Backslash escaping is shell-level; subprocess with shell=False does not interpret shell escapes