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

Also available as: JSON · Markdown
92%Fix Rate
93%Confidence
4Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

subprocess.run() with shell=False splits path containing spaces into multiple arguments instead of treating it as one path.

generic

Workarounds

  1. 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

  2. 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:

  1. Use os.system() instead of subprocess 90% fail

    os.system() is less secure (shell injection) and has the same quoting issues

  2. Add backslash escapes to the path string 85% fail

    Backslash escaping is shell-level; subprocess with shell=False does not interpret shell escapes