enjoi4life411
enjoi4life411

Reputation: 684

Subprocess.run does not work on Windows with file names containing spaces

I am using Powershell in Windows 10

>>> import os, subprocess
>>> os.listdir('C:\\Program Files') # works
>>> subprocess.run('ls C:\\') # works
>>> subprocess.run('ls C:\\Program Files') # Fails

I have tried forward slashes, escaping, 'r' to make a regex, the string enclosed within quotes, and nothing seems to work.

Upvotes: 0

Views: 1367

Answers (2)

kindall
kindall

Reputation: 184171

By passing your command as a single string, you're leaving it to Python to break up the command into arguments. You can either quote the argument that contains spaces as shown by @Kraigolas, or simply break up the command yourself and pass a list of the command and its arguments. I favor this approach because it is easy to use with variables without worrying about having to quote them.

subprocess.run(["ls", r"C:\Program Files"])

Upvotes: 2

Kraigolas
Kraigolas

Reputation: 5560

That won't work in the terminal either. You should quote the file path in the subprocess command:

subprocess.run('ls "C:\\Program Files"')

Everything in those quotes is then read as a single term.

Upvotes: 2

Related Questions